public class 字符串反转 {
public static void main(String[] args) {
String s = "abcdef";
char[] a = s.toCharArray();
//reverse1(a);
//reverse2(a);
reverse3(a);
System.out.println(Arrays.toString(a));
}
private static void reverse3(char[] str) {
int i,j;
assert( str != null );
i = 0;
j = str.length - 1;
while( i < j ){
str[i] = (char) (str[i] + str[j]);
str[j] = (char) (str[i] - str[j]);
str[i] = (char) (str[i] - str[j]);
i++;
j--;
}
}
private static void reverse2(char[] aStr) {
int len = aStr.length;
int mid = len / 2;
char temp;
for (int i = 0; i < mid; ++i){
temp = aStr[i];
aStr[i] = aStr[len -i -1];
aStr[len -i -1] = temp;
}
}
private static void reverse1(char[] aStr) {
for (int i=0,j=aStr.length-1;i<j;i++,j--)
{
aStr[i]^=aStr[j];
aStr[j]^=aStr[i];
aStr[i]^=aStr[j];
}
}
}
Java实现字符串的三种方法(不用类库)
最新推荐文章于 2023-05-03 00:30:00 发布