0

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;

}

5
  • 1
    Not a native way but some ideas: stackoverflow.com/questions/956199/… Commented Nov 16, 2012 at 13:19
  • 2
    native is probably not that best word to use since it has its own meaning in Java. Commented Nov 16, 2012 at 13:19
  • 1
    on an unrelated note, you can improve performance by using arr[x]^=arr[y]; arr[y]^=arr[x]; arr[x]^=arr[y]; Commented Nov 16, 2012 at 13:24
  • @PicklishDoorknob is that really faster than simple assignments? Commented Nov 16, 2012 at 13:42
  • Yes, you don't have to create a temp variable and they are both three commands. Commented Nov 16, 2012 at 13:42

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.