对String字符串进行反序输出

对String字符串进行反序输出

//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);  
        }  
    }  
posted @ 2020-03-23 16:37  昂迪梵德  阅读(1751)  评论(0编辑  收藏  举报