How do I reverse a string?
Category: java.lang, viewed: 4675 time(s).
Below is an example code that reverse a string. Here we use a StringBuffer.reverse() method to reverse a string. In a 1.5 version a new class called StringBuilder also has a reverse() method that do just the same, one of the difference is StringBuffer class is synchronized while StringBuilder class does not.
Beside using this simple method you can try to reverse a string by converting it to character array and then reverse the array order. So here is the string reverse in the StringBuffer way.
package org.kodejava.example.lang; public class StringReverseExample { public static void main(String[] args) { // The normal sentence that is going to be reversed. String words = "Morning of The World - The Last Paradise on Earth"; // To reverse the string we can use the reverse() method in the // StringBuffer class. The reverse() method returns a StringBuffer so // we need to call the toString() method to get a string object. String reverse = new StringBuffer(words).reverse().toString(); // Print the normal string System.out.println("Normal : " + words); // Print the string in reversed order System.out.println("Reverse: " + reverse); } } |
And below is the result.
Normal : Morning of The World - The Last Paradise on Earth Reverse: htraE no esidaraP tsaL ehT - dlroW ehT fo gninroM
Related Examples
- How do I read system property as an integer?
- How do I decode string to integer?
- How do I insert a string in the StringBuilder?
- How do I remove substring from StringBuilder?
- How do I reverse a string by word?
- How do I convert varargs to an array?
- How do I remove trailing white space from a string?
- How do I remove leading white space from a string?
- How do I create a method that accept varargs in Java?
- How do I know a class of an object?
|
|