Swapping Characters of a String in Java



For swapping characters of a string in Java we can use string builder which is mutable so we need not to take care of new object creation during swapping.

In this we would create a method which swap characters of string based on location of swapping characters.This method will take location of swapping characters as its parameters.First store both characters need to be swapped and using set character method of string builder swap the targeted characters.

Example

Live Demo

public class SwapCharacters {
   public static void main(String[] args) {
      String str = "abcde";
      System.out.println(swap(str,0,1));
      System.out.println(swap(str,0,str.length()-1));
   }
   static String swap(String str , int i , int j ) {
      StringBuilder strB = new StringBuilder(str);
      char l = strB.charAt(i) , r = strB.charAt(j);
      strB.setCharAt(i,r);
      strB.setCharAt(j,l);
      return strB.toString();
   }
}

Output

bacde
ebcda

Advertisements