Pratik
Pratik

Reputation: 167

Find sequence of character in word/String and replace with the its occurrence number

Case 1:

String str = "Test something Test";

I have to find Test and replace with it's occurrence number. Here Test appears two time. So the first occurrence shall be replaced with 1 and second occurrence replace with 2.

Expected output

"1 something 2"

This is just small string. It may contain more occurrence of Test in string/word.

Case 2:

String str = "TestsomethingTest";

Expected output

"1something2"

I tried with replace but it replace all occurrence with same number.

Upvotes: 0

Views: 100

Answers (2)

daggett
daggett

Reputation: 28624

Use replaceAll with 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 }

Upvotes: 1

user11044402
user11044402

Reputation:

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);

Upvotes: 3

Related Questions