Java实现给定字符串的倒序输出

1.除2判中法:

public static String orderDesc(String str){
       byte [] bytes = str.getBytes();
       for ( int i = 0; i < bytes.length / 2 ; i++) {
             Byte b = bytes [i] ;
             bytes [i] = bytes [bytes.length - 1 -i ] ;
             bytes [bytes.length - 1 -i ] = b ;
       }
       return new String (bytes) ;
}

2.String类的toCharArray();

public static String orderDesc(String str){
      char[] charArray = str.toCharArray(); 
      String newStr = "";
      for (int i=charArray.length-1; i>=0; i--){ 
        newStr += charArray[i]; 
      } 
      return newStr;
}

3.递归方法

public static void orderDesc (String str){ 
      if (str.length() == 1){ 
          System.out.print(str); 
      }else{
          String str1 = str.substring(0, str.length()-1); 
          String str2 = str.substring(str.length()-1); 
          System.out.print(str2); 
          orderDesc3 (str1); 
      }
} 

4.StringBuffer类的reverse();

public static StringBuffer orderDesc(String str){
      StringBuffer sb = new StringBuffer (str);
      return sb.reverse();
}

 

posted @ 2016-07-01 15:09  如果屈原会编程  阅读(1161)  评论(0编辑  收藏  举报