Java String ReplaceFirst

Hed*_*box 15 java string split replace

我正在读一个字符串

Is Mississippi a State where there are many systems.
Run Code Online (Sandbox Code Playgroud)

我想用"t"或"T"替换每个单词中的第一个"s"或"S"(即保持相同的情况)...以便输出为:

It Mitsissippi a Ttate where there are many tystems.
Run Code Online (Sandbox Code Playgroud)

我试过了

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

并且已经尝试尝试使用字符串[]分割字符串.split(Pattern.quote("\\s")),然后试图找出如何replaceFirst()的每一个元素array,然后返回值回string[ 但不能想出这样做的正确的方式.

我认为\\G可能有助于重新开始下一个单词,但没有在哪里.任何使用这3种方法的帮助表示赞赏.

Tim*_*sen 10

一种选择是分裂串入的话,然后用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());
Run Code Online (Sandbox Code Playgroud)

输出:

It Mitsissippi a Ttate where there are many tystems.
Run Code Online (Sandbox Code Playgroud)


mmu*_*hid 4

Approach-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);
Run Code Online (Sandbox Code Playgroud)

编辑:方法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. 
Run Code Online (Sandbox Code Playgroud)

注意:我更喜欢方法 1,因为它没有方法and replaceFisrtsplitStringappendconcat