OneMoreError
OneMoreError

Reputation: 7728

API method for swapping characters inside a string in Java

Is there a native method in Java to do character swapping inside Strings. I mean, I need to write a function like this everytime and its pretty boring:


    public static String modifyString(String str,int x,int y){

    char arr[]=str.toCharArray();
    char t= arr[x];
    arr[x]=arr[y];
    arr[y]=t;

    String s= new String(arr);
    return s;

}

Upvotes: 0

Views: 432

Answers (1)

mre
mre

Reputation: 44240

No, the String class does not contain a method for swapping characters. Unfortunately, you'll either need to roll your own, or look into using a third party library.

Upvotes: 1

Related Questions