How to swap String characters in Java?

后端 未结 14 2211
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-08 14:22

How can I swap two characters in a String? For example, \"abcde\" will become \"bacde\".

相关标签:
14条回答
  • 2020-12-08 15:02

    String.toCharArray() will give you an array of characters representing this string.

    You can change this without changing the original string (swap any characters you require), and then create a new string using String(char[]).

    Note that strings are immutable, so you have to create a new string object.

    0 讨论(0)
  • 2020-12-08 15:08
    static String  string_swap(String str, int x, int y)
    {
    
        if( x < 0 || x >= str.length() || y < 0 || y >= str.length())
        return "Invalid index";
    
        char arr[] = str.toCharArray();
        char tmp = arr[x];
        arr[x] = arr[y];
        arr[y] = tmp;
    
        return new String(arr);
    }
    
    0 讨论(0)
提交回复
热议问题