Swapping Characters of a String in Java

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.

In this article we would go through some methods to swap character of a given String and get a new String (with swapped characters) while the original String remains unaffected.



Through the examples below lets see some of the method by which we can swap character an generate new String
Examples:
Method 1 (Using toCharArray)
In this method we convert the String into the Character array and perform the required Swaping.

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to demonstrate character swap
// using toCharArray().
public class GFG {
    static char[] swap(String str, int i, int j)
    {
        char ch[] = str.toCharArray();
        char temp = ch[i];
        ch[i] = ch[j];
        ch[j] = temp;
        return ch;
    }
  
    public static void main(String args[])
    {
        String s = "geeksforgeeks";
  
        System.out.println(swap(s, 6, s.length() - 2));
        System.out.println(swap(s, 0, s.length() - 1));
  
        System.out.println(s);
    }
}

chevron_right


Output:

geeksfkrgeeos
seeksforgeekg
geeksforgeeks

Method 2 (Using subString())
We build the modified string using substrings of given string.

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to demonstrate character swap
// using subString()
  
public class GFG {
    static String swap(String str, int i, int j)
    {
        if (j == str.length() - 1)
            return str.substring(0, i) + str.charAt(j)
                + str.substring(i + 1, j) + str.charAt(i);
  
        return str.substring(0, i) + str.charAt(j)
            + str.substring(i + 1, j) + str.charAt(i)
            + str.substring(j + 1, str.length());
    }
  
    public static void main(String args[])
    {
        String s = "geeksforgeeks";
  
        System.out.println(swap(s, 6, s.length() - 2));
        System.out.println(swap(s, 0, s.length() - 1));
  
        // Original String doesn't change
        System.out.println(s);
    }
}

chevron_right


Output:

geeksfkrgeeos
seeksforgeekg
geeksforgeeks

Method 3 (Using StringBuilder or StringBuffer)
In this method either you can use StringBuilder or StringBuffer depending on the situation. See String vs StringBuilder vs StringBuffer in Java to decide when to use which one.

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to demonstrate character swap
// using StringBuilder
  
public class GFG {
    static String swap(String str, int i, int j)
    {
        StringBuilder sb = new StringBuilder(str);
        sb.setCharAt(i, str.charAt(j));
        sb.setCharAt(j, str.charAt(i));
        return sb.toString();
    }
  
    public static void main(String args[])
    {
        String s = "geeksforgeeks";
  
        System.out.println(swap(s, 6, s.length() - 2));
        System.out.println(swap(s, 0, s.length() - 1));
  
        // Original String doesn't change
        System.out.println(s);
    }
}

chevron_right


Output:

geeksfkrgeeos
seeksforgeekg
geeksforgeeks

Output:

geeksfkrgeeos
seeksforgeekg
geeksforgeeks

This article is contributed by Sumit Ghosh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

java-img




My Personal Notes arrow_drop_up