Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java replace string with increasing number

Tags:

java

replace

I want to replace "a" of "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 poor efficiency,when the string is large enough,it will take minutes!

do you have a high efficiency way? thanks very much!

like image 810
chandler Avatar asked Apr 03 '12 09:04

chandler


1 Answers

Use a Matcher to find and replace the 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
like image 104
dacwe Avatar answered Oct 18 '22 23:10

dacwe