Java基础知识强化08:将字符串倒序输出(包括空格)的几种方法

1.最容易想到的估计就是利用String类的toCharArray(),再倒序输出数组的方法了:

 1 package himi.hebao05;
 2 
 3 public class TestDemo02 {
 4     public static void main(String[] args) {
 5         int i = 0;
 6         String text = "hebao I love you!";
 7         String result = " ";
 8         char[] charArray = text.toCharArray();
 9         for(int j = charArray.length-1; j>=0; j--) {
10                 result += charArray[j];
11         }
12         System.out.println(result);
13     }
14   }  

这里将String字符串类型的数据(末尾没有)转化为char[]字符数组,这样就可以一个个控制倒序输出:结果如下:

2.字符串定义为String类,转化为一个StringBuffer类,用StringBuffer类中的reverse()方法直接倒序字符串。

 1 package himi.hebao05;
 2   
 3 public class TestDemo02 {
 4      public static void main(String[] args) {
 5           int i = 0;
 6           String text = "hebao I love you!";
 7              reverseString1(text);
 8       }
 9      
10      
11      public static void reverseString1(String text) {
12          StringBuffer stringBuffer = new StringBuffer(text);
13          System.out.print(stringBuffer.reverse());
14      }
15      
16  }

运行的结果如下:

3. 对字符串转化为byte[],byte[]是将字符串每个字符存储为byte类型,但是不是char类型。所以这里不能直接倒序输出(不能类似1那样)。但是我们可以将字符串转化为byte[]之后进行元素的首尾对称交换,这样可以实现倒序输出的目的:

 1 package himi.hebao05;
 2 
 3 public class TestDemo02 {
 4     public static void main(String[] args) {
 5         int i = 0;
 6         String text = "hebao I love you!";
 7         System.out.println(reverseString2(text));
 8 
 9     }
10     
11     public static String  reverseString2(String text) {
12         if(text == null || text.length() <0 ) {
13             return "ERROR";
14         }
15         byte[] bytes = text.getBytes();
16         for(int i=0; i<bytes.length/2; i++) {
17             byte b= bytes[i];
18             bytes[i] = bytes[bytes.length-1-i];
19             bytes[bytes.length-1-i] = b;
20         }
21         
22         return  new String(bytes);
23     }
24 
25 }

输出结果如下:

4. 也可以使用第三方工具包StringUtils中的字符串反转方法

原文地址:https://www.cnblogs.com/hebao0514/p/4771318.html