我的目标是将句子中“java”一词的任何形式更改为“JAVA”。我已经完成了所有操作,但我的代码无法在混合大小写下读取,例如:JaVa、JAva 等。我知道我应该使用 toUpperCase 和 toLowerCase 或 equalsIgnoreCase 但我不确定如何正确使用它。我不允许使用replace或replace all,老师想要substring方法。
Scanner input=new Scanner(System.in);
System.out.println("Enter a sentence with words including java");
String sentence=input.nextLine();
String find="java";
String replace="JAVA";
String result="";
int n;
do{
n=sentence.indexOf(find);
if(n!=-1){
result =sentence.substring(0,n);
result=result +replace;
result = result + sentence.substring(n+find.length());
sentence=result;
}
}while(n!=-1);
System.out.println(sentence);
}
}
最佳答案
您不能使用 String.indexOf
来执行此操作,因为它区分大小写。
简单的解决方案是使用具有不区分大小写模式的正则表达式;例如
Pattern.compile(regex, Pattern.CASE_INSENSITIVE).matcher(str).replaceAll(repl);
这还有一个好处,可以避免您当前用于替换的困惑字符串攻击。
在您的示例中,您的输入字符串作为正则表达式也是有效的...因为它不包含任何正则表达式元字符。如果确实如此,那么简单的解决方法是使用 Pattern.quote(str)
它将元字符视为文字匹配。
String.replaceAll(...)
是一种用于对字符串进行正则表达式替换的“便捷方法”,这一点也毫无值(value),尽管您不能在示例中使用它,因为它区分大小写匹配。
郑重声明,这是通过字符串攻击完成这项工作的部分解决方案。 @ben - 这是供您阅读和理解的……而不是复制。故意取消注释是为了鼓励您仔细阅读。
// WARNING ... UNTESTED CODE
String input = ...
String target = ...
String replacement = ...
String inputLc = input.lowerCase();
String targetLc = target.lowerCase();
int pos = 0;
int pos2;
while ((pos2 = inputLc.indexOf(targetLc, pos)) != -1) {
if (pos2 - pos > 0) {
result += input.substring(pos, pos2);
}
result += replacement;
pos = pos2 + target.length();
}
if (pos < input.length()) {
result += input.substring(pos);
}
对于结果
使用StringBuilder
可能比使用String
更有效。
关于java - 忽略大写/小写字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27240645/