标签:ring builder void 方式 字符 substring 递归 char int
1 public class StringReverse { 2 public static void main(String[] args) { 3 String str="hello"; 4 System.out.println(reverse(str)); 5 6 } 7 public static StringBuilder reverse(String str){ 8 return new StringBuilder(str).reverse(); 9 } 10 }
1 public class StringReverse { 2 public static void main(String[] args) { 3 String str="hello"; 4 System.out.println(reverse(str)); 5 6 } 7 public static String reverse(String str){ 8 int len=str.length(); 9 if(len==1) 10 return str; 11 //subString(1)表示把字符串中索引1之后的字串拿出来;charAt(0)表示取字符串的第一个字符 12 return reverse(str.substring(1))+str.charAt(0); 13 } 14 }
1 public class StringReverse { 2 public static void main(String[] args) { 3 String str="hello"; 4 System.out.println(reverse(str)); 5 6 } 7 public static String reverse(String str){ 8 String ans=""; 9 for(int i=str.length()-1;i>=0;i--){ 10 char c=str.charAt(i); 11 ans+=c; 12 } 13 return ans; 14 } 15 }
1 public class StringReverse { 2 public static void main(String[] args) { 3 String str="hello"; 4 System.out.println(reverse(str)); 5 6 } 7 public static String reverse(String str){ 8 char[] chars = str.toCharArray(); 9 String ans=""; 10 for (int i = chars.length - 1; i >= 0; i--) { 11 ans+=chars[i]; 12 } 13 return ans; 14 } 15 }
标签:ring builder void 方式 字符 substring 递归 char int
原文地址:https://www.cnblogs.com/treasury/p/12593600.html