Java program to swap character of a string

As we realize that Object of String in Java is permanent (for example we can't play out any progressions once its made). 

To do adjustments on string put away in a String object, we duplicate it's anything but a person exhibit, StringBuffer, and so on, and do alterations on the duplicate item. 

In this article, we would go through certain techniques to trade characters of a given String and get another String (with traded characters) while the first String stays unaffected. 

Through the models beneath how about we see a portion of the strategies by which we can trade characters and produce new String

Examples:

Method 1 (Using toCharArray)

In this strategy we convert the String into the Character cluster and play out the necessary Swaping.

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

Output:

geeksfkrgeeos
seeksforgeekg
geeksforgeeks

Method 2 (Using subString())

We build the modified string using substrings of given string.

 

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

Output:

geeksfkrgeeos
seeksforgeekg
geeksforgeeks

Method 3 (Using StringBuilder or StringBuffer)

In this method, you can use StringBuilder or StringBuffer according to the situation. See String, StringBuilder, and StringBuffer in Java to decide when to use which one.

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

Output:

geeksfkrgeeos
seeksforgeekg
geeksforgeeks

Output:

geeksfkrgeeos
seeksforgeekg
geeksforgeeks

 

Submit Your Programming Assignment Details