gpt4 book ai didi

java - 忽略大写/小写字符串

转载 作者:行者123 更新时间:2023-11-30 07:04:53 25 4
gpt4 key购买 nike

我的目标是将句子中任何形式的单词“java”更改为“JAVA”。我已经完成了所有工作,但我的代码无法在混合情况下读取,例如:Java、JAva 等。我知道我应该使用 toUpperCase 和 toLowerCase 或 equalsIgnoreCase 但我不确定如何正确使用它。我不允许使用替换或全部替换,老师要子字符串方法。

    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(...) 是对字符串进行正则表达式替换的“便捷方法”,但您不能将它用于您的示例,因为它进行区分大小写的匹配。


作为记录,这里有一个部分解决方案,它通过字符串攻击来完成这项工作。 @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);
}

对于 result 使用 StringBuilder 而不是 String 可能更有效。

关于java - 忽略大写/小写字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27240645/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com