首页 > 代码库 > java 反取字符串
java 反取字符串
public class demo2 {
/**
* 2 : 将字符串反取出来 新中国好 好国中新
*/
public static void main(String[] args) {
String s = "新中国好";
s = reverse1(s);
System.out.println("方法一:" + s);
s = reverse2(s);
System.out.println("方法二:" + s);
s = reverse3(s);
System.out.println("方法三:" + s);
}
public static String reverse1(String s) {
int len = s.length();
if (len <= 1) {
return s;
}
String left = s.substring(0, len / 2);
String right = s.substring(len / 2, len);
return reverse1(right) + reverse1(left);
}
public static String reverse2(String s) {
char[] array = s.toCharArray();
String reverse = "";
for (int i = array.length - 1; i >= 0; i--) {
reverse += array[i];
}
return reverse;
}
public static String reverse3(String s) {
return new StringBuffer(s).reverse().toString();
}
}
java 反取字符串