Reverse words in a String in Java

Reversing words in a string


An example on reversing words not letters, in a string in Java.


Example


import java.util.*;
class ReverseWords
{
public static void main(String args[])
{

// Create Scanner object
Scanner s=new Scanner(System.in);

// Take no.of strings that the user wants
int n=s.nextInt();

// Create a temp array
        String temps[]=new String[n];

// Initialize the variable before the user input is stored in it
String st="";

// Create a words array
String words[];

// Skip first line, if not used user input will be skipped one time
s.nextLine();

// Read the no.of strings that user wish to..
for(int k=0;k<n;k++)
{

System.out.println("String #"+(k+1)+": ");

// Read line
st=s.nextLine();

// Split words with a space, because words has spaces at
start, end positions.
words=st.split(" ");

// Initialize temps[k] to avoid null
temps[k]="";

// Reverse string now!
for(int i=words.length-1;i>=0;i--)
{

// Put each word in user input string from end
to start with a space
temps[k]+=words[i]+" ";

}
}

// Now print the words!
for(int i=0;i<n;i++)
{

// Print the reversed strings, trim them to avoid space at
last, see in the reverse logic loop, space is attached at last!
System.out.println("String #"+(i+1)+": "+temps[i].trim
());

}
}
}

Quick Alternative: Without all this logic, you can also use my java-utils framework for doing operations. The gowtham.gutha.util.StringOps class contains methods to achieve this in a single method call.

Also see my previous post on Reversing a string in Java for more help.

No comments: