码迷,mamicode.com
首页 > 编程语言 > 详细

Java字符串反转常见的几种方式?

时间:2020-03-29 18:17:09      阅读:77      评论:0      收藏:0      [点我收藏+]

标签:ring   builder   void   方式   字符   substring   递归   char   int   

(1)通过StringBuilder的reverse()方法,速度最快:

 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 }

(2)通过递归实现,比较高大上:

 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 }

(3)通过charAt()方法:

 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 }

 

(4)通过String的toCharArray()方法

 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 }

 

Java字符串反转常见的几种方式?

标签:ring   builder   void   方式   字符   substring   递归   char   int   

原文地址:https://www.cnblogs.com/treasury/p/12593600.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!