Requirement: For a character string abcd
, the position 0
and position 2
of 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);
}