tags:

views:

1801

answers:

5

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

A: 

String.replaceAll() or replaceFirst()

String s = "abcde".replaceAll("ab", "ba")

Link to the JavaDocs String API

AgileJon
This assumed that you will know the characters to be swapped ahead of time, which doesn't seem like a usable solution in most cases.
byte
+6  A: 

'In' a string, you cant. Strings are immutable. You can easily create a second string with:

 String second = first.replaceFirst("(.)(.)", "$2$1");
toolkit
Lol. Boobies....
Visage
I like the look of your regular expression.
JeeBee
Visage! No! :-)
toolkit
+14  A: 

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
coobird
Nice. Not sure why I went straight to StringBuilder instead of thinking about a char array.
Jon Skeet
@Jon Skeet: My first thought was actually to build up a new String, but since the requirements were a swap, so I thought the char array would be easier. :)
coobird
Arrays, so old fashioned!!!
jjnguy
@jjnguy: Hehe, true, but it gets the job done ;)
coobird
Just to add, the String class uses a char[] to keep its string data internally. This can be seen from browsing the source for the OpenJDK. So it may be old-fashioned, but arrays are used in the String class itself.
coobird
A: 

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.

Brian Agnew
A: 

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();
    }
}