1. The easiest estimate is to use the ToCharArray () of the String classand then reverse the method of outputting the array:
1 Packagehimi.hebao05;2 3 Public classTestDemo02 {4 Public Static voidMain (string[] args) {5 inti = 0;6String Text = "Hebao I love you!";7String result = "";8 Char[] Chararray =Text.tochararray ();9 for(intj = chararray.length-1; j>=0; j--) {TenResult + =Chararray[j]; One } A System.out.println (result); - } -}
Here, the string string type of data (not at the end) is converted to a char[] character array, so that you can control the reverse output: The result is as follows:
2. The string is defined as a string class, converted to a StringBuffer class, using the reverse () method in the StringBuffer class to reverse the string directly.
1 Packagehimi.hebao05;2 3 Public classTestDemo02 {4 Public Static voidMain (string[] args) {5 inti = 0;6String Text = "Hebao I love you!";7 8 reverseString1 (text);9 }Ten One A Public Static voidreverseString1 (String text) { -StringBuffer StringBuffer =NewStringBuffer (text); - System.out.print (Stringbuffer.reverse ()); the } - -}
The results of the operation are as follows:
3. Convert a string to byte[], byte[] is to store each character of the string as a byte type, but not a char type. So there is no direct reverse output (not like 1). However, we can convert the string to byte[] , and then we can exchange the elements in the end of the symmetry, so that the reverse output is achieved:
1 Packagehimi.hebao05;2 3 Public classTestDemo02 {4 Public Static voidMain (string[] args) {5 inti = 0;6String Text = "Hebao I love you!";7 System.out.println (reverseString2 (text));8 9 }Ten One Public Staticstring ReverseString2 (string text) { A if(Text = =NULL|| Text.length () <0 ) { - return"ERROR"; - } the byte[] bytes =text.getbytes (); - for(inti=0; i<bytes.length/2; i++) { - byteb=Bytes[i]; -Bytes[i] = bytes[bytes.length-1-i]; +Bytes[bytes.length-1-i] =b; - } + A return NewString (bytes); at } - + }
The output results are as follows:
Java Fundamentals Hardening 08: Several ways to output strings in reverse (including spaces)