Thursday, April 10, 2008

Reverse a String in Java
This 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
all the best !!!!!!

0 comments:

 
 
Copyright © FREE JAVA TUTORIAL