[英]Java replace string with increasing number
我想用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;
但效率很低,當字符串足夠大時,需要幾分鍾!
你有高效的方式嗎? 非常感謝!
使用Matcher
查找並替換a
:
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);
}
輸出:
001b002b003b004b005b006b007b008b
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.