问题是,在删除“rawr”后,您会移动到 String 中的下一个位置,而忽略您的 String 已更改并且需要在同一位置再次检查的事实。
看一看
>xxxrawrrawrawr
^we are here now and we will remove "rawr"
so we will get
>xxxrawrawr
^do we want to move to next position, or should we check again our string?
试试这种方式:
public static String noRawr(String str) // 7
{
String result = str;
for (int i = 0; i < result.length() - 3; ) {// I move i++ from here
if (result.substring(i, i + 4).equals("rawr")) {
result = result.substring(0, i) + result.substring(i + 4);
}else{
i++; //and place it here, to move to next position
//only if there wont be any changes in string
}
}
return result;
}
测试:
public static void main(String[] args) {
String[] data = {"hellorawrbye","rawrxxx","xxxrawr","rrawrun","rawrxxxrawrrawrawr"};
for (String s : data) {
System.out.println(s+ " -> " + noRawr(s));
}
}
输出:
hellorawrbye -> hellobye
rawrxxx -> xxx
xxxrawr -> xxx
rrawrun -> run
rawrxxxrawrrawrawr -> xxxawr