I want to swap two letters in a string. For example, if input is W and H then all the occurrences of W in string should be replaced by H and all the occurrences of H should be replaced by W. String WelloHorld will become HelloWorld.
I know how to replace single char:
str = str.replace('W', 'H');
But I am not able to figure out how to swap characters.
解决方案
You would probably need three replace calls to get this done.
The first one to change one of the characters to an intermediate value, the second to do the first replace, and the third one to replace the intermediate value with the second replacement.
String str = "Hello World";
str = star.replace("H", "*").replace("W", "H").replace("*", "W");
Edit
In response to some of the concerns below regarding the correctness of this method of swapping characters in a String. This will work, even when there is a * in the String already. However, this requires the additional steps of first escaping any occurrence of * and un-escaping these before returning the new String.
public static String replaceCharsStar(String org, char swapA, char swapB) {
return org
.replace("*", "\\*")
.replace(swapA, '*')
.replace(swapB, swapA)
.replaceAll("(?
.replace("\\*", "*");
}
Edit 2
After reading through some the other answers, a new version, that doesn't just work in Java 8, works with replacing characters which need to be escaped in regex, e.g. [ and ] and takes into account concerns about using char primitives for manipulating String objects.
public static String swap(String org, String swapA, String swapB) {
String swapAEscaped = swapA.replaceAll("([\\[\\]\\\\+*?(){}^$])", "\\\\$1");
StringBuilder builder = new StringBuilder(org.length());
String[] split = org.split(swapAEscaped);
for (int i = 0; i < split.length; i++) {
builder.append(split[i].replace(swapB, swapA));
if (i != (split.length - 1)) {
builder.append(swapB);
}
}
return builder.toString();
}