Reverse Words and Letters in String

The following example illustrates reversing words and letters in a string. This is in fact a Google interview question and now it's solved in Java.

// import for java.util.Scanner class
import java.util.*;
class GoogleReverseString
{
public static void main(String args[])
{

// Create Scanner object for taking input from cmd
Scanner s=new Scanner(System.in);


// Read input from the user
String st=s.nextLine();


// Create StringBuffer object for st
StringBuffer sb=new StringBuffer(st);


// Print the reversed string
System.out.println("Reversed String is "+sb.reverse());

// Split the word with a space
String[] w=sb.toString().split(" ");

String temp="";

for(int i=w.length-1;i>=0;i--)
{
temp+=w[i]+" ";
}

// Trim extra space & print
System.out.println(temp.trim());

}
}

Sample Output


Gowtham Gutha
Reversed String is ahtuG mahtwoG
mahtwoG ahtuG

Also see Reverse words in String and also Reverse a string in Java

No comments: