对于使用Java字符串反转有以下几种实现:
- 利用StringBuilder类中的reverse函数;
- 使用递归,将String的首字符放到除首字符外的子串后,然后再递归调用子串;
- 使用字符数组做reverse;
public class Reverse { public static String reverse1(String str) { if (str == null || str.length() <= 1) return str; return new StringBuilder(str).reverse().toString(); } public static String reverse2(String str) { if (str == null || str.length() <= 1) return str; return reverse2(str.substring(1)) + str.charAt(0); } public static String reverse3(String str) { if (str == null || str.length() <= 1) return str; char[] ca = new char[str.length()]; for (int i = 0; i < str.length(); i++) { ca[i] = str.charAt(str.length() - i - 1); } return new String(ca); } public static void main(String[] args) { String s = "hello world"; System.out.println(reverse1(s)); System.out.println(reverse2(s)); System.out.println(reverse3(s)); } }
时间: 2024-08-05 19:44:23