Java String ReplaceFirst

2022-09-03 13:43:01

我正在用字符串阅读

Is Mississippi a State where there are many systems.

我想将每个单词中的第1个“s”或“S”替换为“t”或“T”(即保持相同的大小写)...因此,输出为:

It Mitsissippi a Ttate where there are many tystems.

我试过

s= s.replaceFirst("(?i)S", "t"); [which of course didn't work]

并尝试尝试使用字符串[]拆分字符串,然后尝试弄清楚如何将每个元素返回,然后将值返回给[但无法找出正确的方法]。.split(Pattern.quote("\\s"))replaceFirst()arraystring

我认为在下一个单词时重新启动可能会有所帮助,但无处可去。任何使用这3种方法的帮助都是值得赞赏的。\\G


答案 1

一种选择是将字符串拆分为单词,然后在每个单词上使用,以将 第一次出现的 替换为(或您想要的任何其他字母):String.replaceFirst()st

更新:

我重构了我的解决方案,以找到任何(大写或小写)的第一次出现,并对其应用适当的转换。s

String input = "Is Mississippi a State where there are many systems.";
String[] parts = input.split(" ");
StringBuilder sb = new StringBuilder("");

for (int i=0; i < parts.length; ++i) {
    if (i > 0) {
        sb.append(" ");
    }
    int index = parts[i].toLowerCase().indexOf('s');
    if (index >= 0 && parts[i].charAt(index) == 's') {
        sb.append(parts[i].replaceFirst("s", "t"));
    }
    else {
        sb.append(parts[i].replaceFirst("S", "T"));
    }
}

System.out.println(sb.toString());

输出:

It Mitsissippi a Ttate where there are many tystems.

答案 2

方法-1:无需使用和方法以获得更好的性能。replacesplit

String str = "Is Mississippi a State where there are many systems.";
System.out.println(str);

char[] cArray = str.toCharArray();
boolean isFirstS = true;
for (int i = 0; i < cArray.length; i++) {
    if ((cArray[i] == 's' || cArray[i] == 'S') && isFirstS) {
        cArray[i] = (cArray[i] == 's' ? 't' : 'T');
        isFirstS = false;
    } else if (Character.isWhitespace(cArray[i])) {
        isFirstS = true;
    }
}
str = new String(cArray);

System.out.println(str);

编辑:方法2:由于您需要使用方法并且您不想使用,因此这里有一个选项:replaceFirstStringBuilder

String input = "Is Mississippi a State where there are many Systems.";
String[] parts = input.split(" ");
String output = "";

 for (int i = 0; i < parts.length; ++i) {
     int smallSIndx = parts[i].indexOf("s");
     int capSIndx = parts[i].indexOf("S");

     if (smallSIndx != -1 && (capSIndx == -1 || smallSIndx < capSIndx))
         output += parts[i].replaceFirst("s", "t") + " ";
     else
         output += parts[i].replaceFirst("S", "T") + " ";
 }

System.out.println(output); //It Mitsissippi a Ttate where there are many Tystems. 

注意:我更喜欢方法1因为它没有方法和,字符串或replaceFisrtsplitappendconcat