字符串反转实现
@(技术笔记)[java|算法]
字符串反转实现
- jdk自带方式
- for循环
- 递归
package base.views.json;
/**
* Created by xiaofeng.song on 2014/10/11.
*/
public class TestStringUtils {
public static void main(String args[]) {
System.out.println(reverseFor("你们好"));
System.out.println(reverseJdk("你们好吗?"));
System.out.println(reverseRecursion("你们好吗?么么哒!"));
}
public static String reverseJdk(String str) {
if (str == null || "".equals(str)) {
return str;
}
return new StringBuffer(str).reverse().toString();
}
public static String reverseFor(String str) {
if (str == null || "".equals(str)) {
return str;
}
StringBuffer sb = new StringBuffer();
for (int i = str.length() - 1; i >= 0; i--) {
sb.append(str.charAt(i));
}
return sb.toString();
}
public static String reverseRecursion(String str) {
if (str == null || "".equals(str)) {
return str;
}
StringBuffer sb = new StringBuffer();
return _reverse(sb, str, str.length());
}
private static String _reverse(StringBuffer sb, String str, int length) {
if (length > 0) {
sb.append(str.charAt(length - 1));
length--;
// System.out.println(sb.toString());
String st = _reverse(sb, str, length);
return st;
} else {
return sb.toString();
}
}
}