Java Data Type How to - Swap String characters








Question

We would like to know how to swap String characters.

Answer

public class Main {
  public static void main(String[] args) {
    System.out.println(swapChars("abcde", 0, 1));
  }/*from   w ww.  j ava 2 s  .  c  o  m*/

  private static String swapChars(String str, int lIdx, int rIdx) {
    StringBuilder sb = new StringBuilder(str);
    char l = sb.charAt(lIdx), r = sb.charAt(rIdx);
    sb.setCharAt(lIdx, r);
    sb.setCharAt(rIdx, l);
    return sb.toString();
  }
}