一个快速的解决方案是完全删除您的do/while 循环,只需使用不区分大小写的正则表达式和String.replaceAll(),例如:
sentence = sentence.replaceAll("(?i)java", "JAVA");
System.out.println(sentence);
或者,更一般的,根据你的变量命名:
sentence = sentence.replaceAll("(?i)" + find, replace);
System.out.println(sentence);
Sample Program
编辑:
根据你的cmets,如果你需要使用substring方法,这里有一种方法。
首先,由于String.indexOf进行区分大小写的比较,你可以编写自己的不区分大小写的方法,我们称之为indexOfIgnoreCase()。这个方法看起来像:
// Find the index of the first occurrence of the String find within the String str, starting from start index
// Return -1 if no match is found
int indexOfIgnoreCase(String str, String find, int start) {
for(int i = start; i < str.length(); i++) {
if(str.substring(i, i + find.length()).equalsIgnoreCase(find)) {
return i;
}
}
return -1;
}
那么,您可以通过以下方式使用此方法。
你找到你需要的词的索引,然后你把这个词之前的字符串部分(直到找到的索引)添加到结果中,然后你添加你找到的词的替换版本,然后你添加找到的单词之后的其余字符串。
最后,根据找到的单词的长度更新起始搜索索引。
String find = "java";
String replace = "JAVA";
int index = 0;
while(index + find.length() <= sentence.length()) {
index = indexOfIgnoreCase(sentence, find, index); // use the custom indexOf method here
if(index == -1) {
break;
}
sentence = sentence.substring(0, index) + // copy the string up to the found word
replace + // replace the found word
sentence.substring(index + find.length()); // copy the remaining part of the string
index += find.length();
}
System.out.println(sentence);
Sample Program
您可以使用StringBuilder 来提高效率,因为+ 运算符会在每个连接上创建一个新字符串。 Read more here
此外,您可以将indexOfIgnoreCase 中的逻辑和其余代码组合在一个方法中,例如:
String find = "java";
String replace = "JAVA";
StringBuilder sb = new StringBuilder();
int i = 0;
while(i + find.length() <= sentence.length()) {
// if found a match, add the replacement and update the index accordingly
if(sentence.substring(i, i + find.length()).equalsIgnoreCase(find)) {
sb.append(replace);
i += find.length();
}
// otherwise add the current character and update the index accordingly
else {
sb.append(sentence.charAt(i));
i++;
}
}
sb.append(sentence.substring(i)); // append the rest of the string
sentence = sb.toString();
System.out.println(sentence);