How can I swap two characters in a String? For example, "abcde" will become "bacde". Thanks.
String.replaceAll() or replaceFirst()
String s = "abcde".replaceAll("ab", "ba")
Link to the JavaDocs String API
'In' a string, you cant. Strings are immutable. You can easily create a second string with:
String second = first.replaceFirst("(.)(.)", "$2$1");
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 = s.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
String.toCharArray() will give you an array of characters representing this string.
You can change this without changing the original string (swap any characters you require), and then create a new string using String(char[]).
Note that strings are immutable, so you have to create a new string object.
This has been answered a few times but here's one more just for fun :-)
public class Tmp {
public static void main(String[] args) {
System.out.println(swapChars("abcde", 0, 1));
}
private static String swapChars(String str, int lIdx, int rIdx) {
StringBuilder sb = new StringBuilder(str);
char l = sb.charAt(lIdx), r = sb.charAt(rIdx);
sb.setCharAt(lIdx, r);
sb.setCharAt(rIdx, l);
return sb.toString();
}
}