Swapping Characters of a String in Java
Last Updated :
16 Oct, 2024
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
// 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);
}
}
Outputgeeksfkrgeeos
seeksforgeekg
geeksforgeeks
Method 2 (Using subString())
We build the modified string using substrings of given string.
Java
// 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);
}
}
Outputgeeksfkrgeeos
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.
Java
// 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);
}
}
Outputgeeksfkrgeeos
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
// Java program to demonstrate character swap
// using XOR Operator
public class GFG {
static String swap(String str, int i, int j)
{
char[] ch = str.toCharArray();
// Swapping using XOR operation
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));
// Original String doesn't change
System.out.println(s);
}
}
// This code is contributed by Susobhan Akhuli
Outputgeeksfkrgeeos
seeksforgeekg
geeksforgeeks
Similar Reads
Swapping Pairs of Characters in a String in Java Given string str, the task is to write a Java program to swap the pairs of characters of a string. If the string contains an odd number of characters then the last character remains as it is. Examples: Input: str = âJavaâOutput: aJav Explanation: The given string contains even number of characters.
3 min read
Swap characters in a String Given a String S of length N, two integers B and C, the task is to traverse characters starting from the beginning, swapping a character with the character after C places from it, i.e. swap characters at position i and (i + C)%N. Repeat this process B times, advancing one position at a time. Your ta
14 min read
Convert a String to a List of Characters in Java In Java, to convert a string into a list of characters, we can use several methods depending on the requirements. In this article, we will learn how to convert a string to a list of characters in Java.Example:In this example, we will use the toCharArray() method to convert a String into a character
3 min read
Convert List of Characters to String in Java Given a list of characters. In this article, we will write a Java program to convert the given list to a string. Example of List-to-String ConversionInput : list = {'g', 'e', 'e', 'k', 's'} Output : "geeks" Input : list = {'a', 'b', 'c'} Output : "abc" Strings - Strings in Java are objects that are
4 min read
Print the middle character of a string Given string str, the task is to print the middle character of a string. If the length of the string is even, then there would be two middle characters, we need to print the second middle character. Examples: Input: str = "Java"Output: vExplanation: The length of the given string is even. Therefore,
3 min read
Java Program to Get a Character from a String Given a String str, the task is to get a specific character from that String at a specific index. Examples:Input: str = "Geeks", index = 2Output: eInput: str = "GeeksForGeeks", index = 5Output: F Below are various ways to do so: Using String.charAt() method: Get the string and the indexGet the speci
5 min read