public static String updatedStr(){
String [] ar= {"green","red","purple","black"};
String str="The colors are (blue), (blue), and (yellow). I prefer (orange)";
我想要一个&#34的最终输出字符串;颜色是绿色,红色和紫色。我更喜欢黑色。"
答案 0 :(得分:0)
您可以在不使用replace
的情况下执行此操作。只需迭代输入String
并添加到原始StringBuilder
的{{1}}部分(未包含在括号中)和替换字,而不是括号中包含的部分。
String
此方法返回:
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 ();
}
此代码进行了一些简化假设。例如,替换数组中的元素数量应至少与要替换的单词数一样高。更完整的实现应该包含额外的检查。
答案 1 :(得分:0)
您可以通过计算要替换的位置并将其保存在数组中来执行此操作,如下所示:
public static String updatedStr(){
String [] ar= {"green","red","purple","black"};
String str="The colors are (blue), (blue), and (yellow). I prefer (orange)";
ArrayList<String> arr = new ArrayList<String>();
int pos [] = new int[ar.length]; // save locations here
for(int i = str.indexOf('(', 0); i != -1; i = str.indexOf('(', i + 1)) {
arr.add(str.substring(i + 1, str.indexOf(')', i)));
pos[arr.size()-1] = i; // save it!
}
// replace from right to left
for (int j=pos.length-1;j>=0;j--){
String newStr = str.substring(0, pos[j]+1) + ar[j] + str.substring(str.indexOf(')',pos[j]+1), str.length());
str = newStr;
}
return str;
}
这里的诀窍是我从右到左替换,以便在我替换它时,我需要替换的位置不会移动。