字符串反转
public class TurnOver { public static void main(String[] args) { String str = "abcdefg"; System.out.println("方法1:" + turnOver1(str)); System.out.println("方法2:" + turnOver2(str)); System.out.println("方法3:" + turnOver3(str)); } /** * 使用递归 * * @param str * @return */ private static String turnOver1(String str) { if (str == null || str.length() <= 1) { return str; } return turnOver1(str.substring(1)) + str.charAt(0); } /** * 将字符串转换为数组,将数组倒序 * * @param str * @return */ private static String turnOver2(String str) { char[] arr = str.toCharArray(); String result = ""; for (int i = arr.length - 1; i >= 0; i--) { result += arr[i]; } return result; } /** * 使用StringBuilder的reverse()方法 * * @param str * @return */ private static String turnOver3(String str) { StringBuilder sb = new StringBuilder(str); return sb.reverse().toString(); } }