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


    (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 }
  • 相关阅读:
    整数的位数,及反转
    判断1~n有多少个1
    C语言常用字符串函数
    C语言类型转换原理
    printf()函数压栈a++与++a的输出
    49 丑数( 时间空间效率的平衡)
    42 连续子数组的最大和(时间效率)
    41 数据流中的中位数(时间效率)
    40 最小的K个数(时间效率)
    一、简介 ELO商户类别推荐有助于了解客户忠诚度
  • 原文地址:https://www.cnblogs.com/treasury/p/12593600.html
Copyright © 2020-2023  润新知