字符串倒序输出的五种方法

2023-02-18 00:00:00 字符串 输出 五种
//1. 使用数组循环
public static String array(String s){
        int length=s.length();
        char[] array=s.toCharArray();
        for(int i=0;i<length/2;i++){
            array[i]=s.charAt(length-1-i);
            array[length-1-i]=s.charAt(i);
        }
        return new String(array);       
    }
//2. StringBuffer的reverse方法
public static StringBuffer buffer(String s){
        StringBuffer sb=new StringBuffer();
        sb.append(s);       
        return sb.reverse();
    }
//3. StringBuffer的循环 
    public static String buffer2(String s){
        int length=s.length();
        StringBuffer sb=new StringBuffer();
        for(int i=s.length()-1;i>=0;i--){
            sb.append(s.charAt(i));
        }
        return sb.toString();       
    } //StringBuilder比StringBuffer快,但线程不安全

//4.栈的后进先出
    public static String reverseByStack(String str) {  
        if(str == null || str.length() == 0) {  
            return str;  
        }  
        Stack<Character> strStack = new Stack<Character>();  
        char[] chArray = str.toCharArray();  
        for(Character ch: chArray) {  
            strStack.push(ch);  
        }  
        int len = str.length();  
        for(int i= 0; i< len; i++) {  
            chArray[i] = strStack.pop();  
        }  
        return new String(chArray);  
    }  
5.  迭代完成
    public static String reverseByRecursive(String str) {  
      if(str == null || str.length() == 0) {  
           return str;  }  
      int len = str.length();  
      if(len == 1) {  
         return str;  
      } else {  
return reverseByRecursive(str.substring(1))+ str.charAt(0);  
        }  
    }  
    原文作者:成功人士从不写博客
    原文地址: https://blog.csdn.net/liyifan687/article/details/80224227
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。

相关文章