This Java tutorial shows how to reverse the contents of a string.
To reverse the contents of a string, we will use the StringBuffer class which has a reverse() method that allows us to easily reverse the contents of the string.
To start we will create a String and place that String into a StringBuffer.
//Original String
String originalString = "Hello World";
//Create a StringBuffer from the original string
StringBuffer buffer = new StringBuffer(originalString);
Next, we will call the reverse method on the StringBuffer and convert the StringBuffer back to a String.
//Reverse the contents of the StringBuffer
buffer = buffer.reverse();
//Convert the StringBuffer back to a String
String reverseString = buffer.toString();
Below is the complete code for reversing the contents of a string.
//Original String String
originalString = "Hello World";
//Create a StringBuffer from the original string
StringBuffer buffer = new StringBuffer(originalString);
//Reverse the contents of the StringBuffer
buffer = buffer.reverse();
//Convert the StringBuffer back to a String
String reverseString = buffer.toString();
//Print the original and reverse string
System.out.println("original: " + originalString);
System.out.println("reverse : " + reverseString);
Below is the output from the sample code above:
original: Hello World
reverse : dlroW olleH
6 comments:
Great post. Extremely intuitive. Thank you. It was exactly what I was looking for.
Very Nice and easy to understand for beginners I liked it.
Thank you very much I hope Posts like these will be very useful an d every one will like it.
Thanks dudeee.. ur the best...
thanks
really its so nice for beginners.
Thank you.It really helps!...
Post a Comment