[英]Find sequence of character in word/String and replace with the its occurrence number
Case 1:情况1:
String str = "Test something Test";
I have to find Test
and replace with it's occurrence number.我必须找到Test
并用它的出现次数替换。 Here Test
appears two time.这里Test
出现了两次。 So the first occurrence shall be replaced with 1
and second occurrence replace with 2
.因此,第一次出现应替换为1
,第二次出现应替换为2
。
Expected output预期 output
"1 something 2"
This is just small string.这只是小字符串。 It may contain more occurrence of Test
in string/word.它可能在字符串/单词中包含更多出现的Test
。
Case 2:案例二:
String str = "TestsomethingTest";
Expected output预期 output
"1something2"
I tried with replace
but it replace all occurrence with same number.我尝试使用replace
,但它用相同的数字替换所有出现。
Try a loop:尝试循环:
String str = "Test something Test";
// Look for the first occurence of "Test".
int idx = str.indexOf("Test");
// Counter that will be used as the replacement.
int i = 1;
// While "Test" was found in the string ...
while (idx >= 0) {
// ... replace it with the current counter value, increase it afterward ...
str = str.replaceFirst("Test", "" + i++);
// ... and find the next occurence of "Test".
idx = str.indexOf("Test");
}
// The result.
System.out.println(str);
Use replaceAll with Closure http://docs.groovy-lang.org/latest/html/groovy-jdk/java/lang/CharSequence.html#replaceAll(java.lang.CharSequence,%20groovy.lang.Closure)将 replaceAll 与 Closure http://docs.groovy-lang.org/latest/html/groovy-jdk/java/lang/CharSequence.html#replaceAll(java.lang.CharSequence,%20groovy.lang.Closure) 一起使用
def s="abc zde abc"
def i=0
println s.replaceAll("abc"){ ++i }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.