gpt4 book ai didi

java - 当子字符串多于值时,将重复出现的子字符串替换为数组值

转载 作者:行者123 更新时间:2023-12-01 11:06:12 25 4
gpt4 key购买 nike

public static String updatedStr()
{
String [] ar= {"green","red","purple","black"};

String str="The colors are (blue), (blue), and (yellow). I prefer (orange)";

StringBuilder out = new StringBuilder ();
int x = 0;
int pos = 0;

for(int i = str.indexOf('(', 0); i != -1; i = str.indexOf('(', i + 1)) {
out.append (str.substring(pos,i)); // add the part between the last ) and the next (
out.append (ar[x++]); // add replacement word
pos = str.indexOf(')', i) + 1;
}

out.append (str.substring(pos)); // add the part after the final )
return out.toString ();
}

我可以用字符串数组中的元素替换括号内的内容。

这里,我实现了输出

"The colors are green, red, and purple. I prefer black."

现在,我正在尝试实现一个场景String [] ar= {"green","re​​d"}

我希望输出为

"The colors are green, red, and (yellow). I prefer (orange)."

如您所见,原始字符串的其余部分保持不变,因为没有足够的值来替换它们。

到目前为止,我已经尝试在 for 循环之前使用 while 循环来防止 ArrayIndexOutOfBoundsError,但实际上我仍然收到该错误。

最佳答案

您只需声明一个新变量来计算已进行的替换次数,并在达到数组长度时停止。

public static String updatedStr()
{
String [] ar= {"green","red"};
String str="The colors are (blue), (blue), and (yellow). I prefer (orange)";

StringBuilder out = new StringBuilder ();
int x = 0;
int pos = 0;
int added=0;
for(int i = str.indexOf('(', 0); i != -1 && added<ar.length; i = str.indexOf('(', i + 1)) {
out.append (str.substring(pos,i)); // add the part between the last ) and the next (
out.append (ar[x++]); // add replacement word
pos = str.indexOf(')', i) + 1;
}
out.append (str.substring(pos)); // add the part after the final )
return out.toString ();
}

关于java - 当子字符串多于值时,将重复出现的子字符串替换为数组值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32917566/

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