Java中字符串倒序


//转换成字符数组逆序输出

public static void stringReverse(String s) {

char[] charArr = s.toCharArray();

String resultStr = "";

for(int i=s.length()-1; i>=0; i--) {

resultStr += charArr[i];

}

System.out.println(resultStr);

}




//转换成字符数组从两头开始交换


public static void stringReverse(String s) {

char[] charArr = s.toCharArray();

char swap;

for(int i=0,j=s.length()-1; i<j; i++,j--) {

swap = charArr[i];

charArr[i] = charArr[j];

charArr[j] = swap;

}

System.out.println(charArr);

}




//递归


public static void stringReverse(String s) {

if(s.length() == 1) {

System.out.print(s);

} else {

String s1 = s.substring(0, s.length()-1);

String s2 = s.substring(s.length()-1);

System.out.print(s2);

stringReverse(s1);

}


}



//将String转换成StringBuffer,然后调用StringBuffer的reverse()方法

public static void stringReverse(String s) {

StringBuffer stringBuffer = new StringBuffer(s);

System.out.println(stringBuffer.reverse());

}



//进栈再出栈

public static void stringReverse(String s) {

Stack stack = new Stack();

char[] charArr = s.toCharArray();

for(int i=0; i<charArr.length; i++) {

stack.push(charArr[i]);

}


while(!stack.empty()) {

System.out.print(stack.pop());

}

}


原文链接: http://blog.csdn.net/justinavril/article/details/2719567

你可能感兴趣的:(String,stringreverse)