How to swap String characters in Java?

user107023 picture user107023 · Jun 5, 2009 · Viewed 101.6k times · Source

How can I swap two characters in a String? For example, "abcde" will become "bacde".

Answer

coobird picture coobird · Jun 5, 2009

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