How to swap String characters in Java?

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

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

14条回答
  •  温柔的废话
    2020-12-08 14:52

    Since String objects are immutable, going to a char[] via toCharArray, swapping the characters, then making a new String from char[] via the String(char[]) constructor would work.

    The following example swaps the first and second characters:

    String originalString = "abcde";
    
    char[] c = originalString.toCharArray();
    
    // Replace with a "swap" function, if desired:
    char temp = c[0];
    c[0] = c[1];
    c[1] = temp;
    
    String swappedString = new String(c);
    
    System.out.println(originalString);
    System.out.println(swappedString);
    

    Result:

    abcde
    bacde
    

提交回复
热议问题