gpt4 book ai didi

Java用递增的数字替换字符串

转载 作者:搜寻专家 更新时间:2023-10-31 19:40:53 24 4
gpt4 key购买 nike

我想用 001,002,003,004 替换“abababababababab”的“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

关于Java用递增的数字替换字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9990162/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com