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 ();
}
我可以用括号数组中的元素替换括号内的任何内容。
在这里,我实现了
的输出"颜色为绿色,红色和紫色。我更喜欢黑色。"
现在,我正在尝试实施一个场景
String [] ar= {"green","red"}
。
我希望输出为
"颜色为绿色,红色和(黄色)。我更喜欢(橙色)。"
如您所见,原始字符串的其余部分保持不变,因为没有足够的值来替换它们。
到目前为止,我尝试在for循环之前使用while循环来阻止ArrayIndexOutOfBoundsError
,但实际上我仍然遇到了这个错误。
答案 0 :(得分:1)
你只需要声明一个新变量来计算已经进行了多少次替换,并在它达到数组长度时停止。
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 ();
}