方法-1:无需使用和方法以获得更好的性能。replace
split
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,因为它没有方法和,字符串或replaceFisrt
split
append
concat