Java replaces string with increasing number

I want to replace "a" with "abababababababab" with 001 002 003 004 ...... that is, "001b002b003b004b005b ....."

int n=1
String test="ababababab";
int lo=test.lastIndexOf("a");
while(n++<=lo) Abstract=Abstract.replaceFirst("a",change(n));
//change is another function to return a string "00"+n;

however, this is low efficiency, when the string is large enough, it will take minutes!

Do you have a high performance way? Many thanks!

+5
source share
1 answer

Use Matcherto find and replace as:

public static void main(String[] args) {

    Matcher m = Pattern.compile("a").matcher("abababababababab");

    StringBuffer sb = new StringBuffer();
    int i = 1;
    while (m.find()) 
        m.appendReplacement(sb, new DecimalFormat("000").format(i++));
    m.appendTail(sb);        

    System.out.println(sb);
}

Outputs:

001b002b003b004b005b006b007b008b
+8
source

All Articles