This example shows how to reverse a given string
public class StringReverseExample { public static void main(String args[]) { // declare one string object. String str = "Hello World"; System.out.println("Original String : " + str); /** * The easiest way to reverse a given string is to use * reverse() method of java StringBuilder class.reverse() * method returns the StringBuilder object so we need to * cast it back to String using toString() method of * StringBuilder **/ str = new StringBuilder(str).reverse().toString(); System.out.println("Reversed String : " + str); } }
The output is:
Original String : Hello World
Reversed String : dlroW olleH
No comments:
Post a Comment