Java swaps the values of two positions in a string

Requirement: For a character string abcd, the position 0and position 2of the two characters are required to be exchanged, and the result of the exchange is cbad.

Java efficient implementation plan, first convert String to char array, the array can modify the value at any position, and perform regular array exchange.

public static void main(String[] args) {
    
    
    String str = "abcd";
    int i = 0, j = 2;
    char[] strArray = str.toCharArray(); // 转换成数组
    char temp = strArray[i];
    strArray[i] = strArray[j];
    strArray[j] = temp;
    str = String.valueOf(strArray);
    System.out.println(str);
}

Guess you like

Origin blog.csdn.net/weixin_43486780/article/details/113759407
Recommended