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

//1. 使用数组循环
public static String array(String s){
        int length=s.length();
        char[] array=s.toCharArray();
        for(int i=0;i2;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 strStack = new Stack();  
        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);  
        }  
    }  

你可能感兴趣的:(java,string倒序,java)