How can I swap two characters in a String? For example, "abcde" will become "bacde".
As we know that Object of String in Java are immutable (i.e. we cannot perform any changes once its created). To do modifications on string stored in a String object, we copy it to a character array, StringBuffer, etc and do modifications on the copy object.
Since String objects are immutable, going to a char[] via toCharArray, swapping the characters, then making a new String from char[] via the String(char[]) constructor would work.
The following example swaps the first and second characters:
String originalString = "abcde"; char[] c = originalString.toCharArray(); // Replace with a "swap" function, if desired: char temp = c[0]; c[0] = c[1]; c[1] = temp; String swappedString = new String(c); System.out.println(originalString); System.out.println(swappedString); Result:
abcde bacde
'In' a string, you cant. Strings are immutable. You can easily create a second string with:
String second = first.replaceFirst("(.)(.)", "$2$1");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With