我想用001,002,003,004替换"ababababababab"的"a"......即"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;
Run Code Online (Sandbox Code Playgroud)
但效率很低,当字符串足够大时,需要几分钟!
你有高效的方式吗?非常感谢!
用a Matcher
来查找和替换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);
}
Run Code Online (Sandbox Code Playgroud)
输出:
001b002b003b004b005b006b007b008b
Run Code Online (Sandbox Code Playgroud)