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!
Use a Matcher
to find and replace the a
s:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With