我正在读一串

Is Mississippi a State where there are many systems.

我想将每个单词中的第一个“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()的每个元素进行array,然后的值返回至string [,但无法找出正确的方法]。

我以为\\G可能有助于在下一个单词处重新启动,但是却无处可去。感谢使用这3种方法的帮助。

最佳答案

方法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:因为您需要使用replaceFirst方法,并且您不想使用StringBuilder,所以这里有一个选项供您选择:
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 ,因为它没有方法replaceFisrtsplit,String appendconcat的开销

07-26 08:31