1、方式一:使用StringBuilder中的api实现字符串反转
public static String reverseStr1(String str) {
StringBuilder sb = new StringBuilder(str);
StringBuilder reverse = sb.reverse();
String s = reverse.toString();
return s;
}
2、方式二:把字符串转成字符数组,接着从尾到头遍历出来
public static String reverseStr2(String str) {
char[] chars = str.toCharArray();
String s = "";
for (int i = chars.length - 1; i >= 0; i--) {
s += chars[i];
}
return s;
}
3、方式三:使用栈的特点(先进后出,后进先出)来实现字符串的反转
public static String reverseStr3(String str) {
String s = "";
Stack stack = new Stack();
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
stack.push(c);
}
System.out.println(stack);
while (!stack.isEmpty()) {
char pop = (char) stack.pop();
s += pop;
}
return s;
}