Swapping Characters of a String in Java
Last Updated :
08 Apr, 2023
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 Swapping.
Java
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 ));
System.out.println(s);
}
}
|
Output:
geeksfkrgeeos
seeksforgeekg
geeksforgeeks
Method 2 (Using subString())
We build the modified string using substrings of given string.
Java
public class GFG {
static String swap(String str, int i, int j)
{
char [] ch = str.toCharArray();
ch[i] = ( char )(ch[i] ^ ch[j]);
ch[j] = ( char )(ch[i] ^ ch[j]);
ch[i] = ( char )(ch[i] ^ ch[j]);
return String.valueOf(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);
}
}
|
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.
Output:
geeksfkrgeeos
seeksforgeekg
geeksforgeeks
Method 4 (Using XOR Operator)
The XOR operator can be used to swap two characters in a string. The idea is to take XOR of both characters and then take XOR of each character with the result again. This will result in swapping of the characters.
This approach works because XOR of any two same number is 0 and XOR of a number X with 0 is X.
Java
public class GFG {
static String swap(String str, int i, int j)
{
char [] ch = str.toCharArray();
ch[i] = ( char )(ch[i] ^ ch[j]);
ch[j] = ( char )(ch[i] ^ ch[j]);
ch[i] = ( char )(ch[i] ^ ch[j]);
return String.valueOf(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);
}
}
|
Output
geeksfkrgeeos
seeksforgeekg
geeksforgeeks
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...