How to reverse words in String Java? [Solution]

In this Java Coding tutorial, you will learn how to reverse words in String. It's also one of the popular coding questions, so you will also learn how to take a requirement, how to fill gaps in the requirement by asking the right question. A String is nothing but a sentence, which may contain multiple works, or just contain a single word or it may be empty. Your program must produce a String contains the word in reverse order , for example if given input is "Java is Great" then your program should return "Great is Java".  Now, if you are a good programmer then you should have some right questions for the programmer. Never assume you know everything, even if its looks a simple problem. Always remember "Devil is in detail". Also asking a question not only fill the gaps in requirement but also help you to make an impression.

One question candidate should definitely ask is, what constitutes a word here? For the purpose of this program, the word is nothing but a sequence of non-space characters. Another good question you can ask to Interview is about input, e.g. is it possible for input string to contain leading or trailing spaces?

Yes, it's possible. However, your reversed string should not any contain leading or trailing spaces. One more important question for Interviewer is about spacing between words, is it possible to have multiple spaces between two words? Yes, it could be possible but you can reduce them to a single space in the reversed string.

BTW, if you preparing for programming job interview, you can also take a look at Cracking the Coding Interview: 150 Programming Questions and Solutions, you will not only find some good question on array and String on this book but also about several other key topics e.g. SQL, database, networking and Java.




Reversing order of words in a Sentence in Java - Solution

Here is our Java solution of this problem. It's simple and straight forward.  In this code example, I have shown two ways to reverse words in a String, first one is using, Java's regular expression support to split the string on spaces and then using reverse() method of Collections utility class. Once you split the String using regex "\\s", it will return you an array of words. It will also handle words separated by multiple spaces, so you don't need to worry.

Once you got the array, you can create an ArrayList from array and then you are eligible to use Collections.reverse() method. This will reverse your ArrayList and you will have all the words in reverse order, now all you need to do is concatenate multiple String by iterating over ArrayList.

I have used StringBuilder for concatenating String here. Also make sure to specify size, because  resizing of StringBuilder is costly as it involves creation of new array and copying content from old to new array.

As I said earlier, for more coding problems from programming interviews, you can also check the Cracking the Coding Interview: 150 Programming Questions and Solutions, one of the best collection of programming interview questions.



Second method is even more easier, instead of using Collections.reverse() method, I have just used traditional for loop and started looping over array from end and performing String concatenation. This way, you even don't need to convert your String array to ArrayList of String. This solution is more memory efficient and faster than previous one.

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
 
/**
 * Java Program to reverse words in String. There are multiple way to solve this
 * problem. you can either use any collection class e.g. List and reverse the
 * List and later create reverse String by joining individual words.
 *
 * @author Javin Paul
 */
public class Testing {
 
  public static void main(String args[]) {
 
  }
 
  /*
  * Method to reverse words in String in Java
  */
  public static String reverseWords(String sentence) {
  List< String> words = Arrays.asList(sentence.split("\\s"));
  Collections.reverse(words);
  StringBuilder sb = new StringBuilder(sentence.length());
 
  for (int i = words.size() - 1; i >= 0; i--) {
  sb.append(words.get(i));
  sb.append(' ');
  }
 
  return sb.toString().trim();
  }
 
  public static String reverseString(String line) {
  if (line.trim().isEmpty()) {
  return line;
  }
 
  StringBuilder reverse = new StringBuilder();
  String[] sa = line.trim().split("\\s");
 
  for (int i = sa.length - 1; i >= 0; i--) {
  reverse.append(sa[i]);
  reverse.append(' ');
  }
 
  return reverse.toString().trim();
  }
}
}


Sometime Interviewer may ask you to solve this problem without using Java Collection framework, because it obviously makes the task a lot easier. So its also good to prepare a solution based upon pure programming logic. If you know how to reverse array in Java, then you have an advantage because String is nothing but a character array, but tricky part is you don't need to reverse array but to reverse words.

How to reverse words in String Java


That's all about how to reverse words in a String sentence in Java. You have learned two ways to reverse order of words. You have also learned how to split String using regex, which is an important skill for Java programmer and you have also learned a good utility method to reverse any Collection in Java. It's good to practice this kind of coding problems both to learn Java and to improve your programming and coding skill. If you are preparing for programming interview, I also suggest to take a look at Programming Interviews Exposed: Secrets to Landing Your Next Job, one of the best book to prepare for programming job interview. You will find several such problems and great explanation in this book.


14 comments:

  1. Can you please share a solution to reverse words in a sentence in place? without using StringBuilder or any additional buffer? I was asked to do so but didn't think of how ti could be done.

    ReplyDelete
    Replies
    1. Below find the small snippet for String reversal without using any of the predefined methods of Java
      public class StringReverse {

      public static void main(String[] args) {

      String word = "This String will be getting reversed";
      String reversedWord="";

      for(int i=word.length()-1;i>=0;i--){
      reversedWord = reversedWord + word.charAt(i);
      }

      System.out.println(" Reversed Word : "+reversedWord);
      }

      }

      ------------------------------------------------

      Reversed Word : desrever gnitteg eb lliw gnirtS sihT

      Delete
  2. i need the program for the output string reverse

    inupt :
    the world is awsome
    output:
    emo swasi dl roweht

    ReplyDelete
  3. import java.util.ArrayDeque;
    import java.util.Scanner;

    public class abc {
    public static void main(String args[]) {
    Scanner scn = new Scanner(System.in);
    System.out.println("Enter string");
    String str = scn.nextLine();
    int count =0;
    char c[] = str.toCharArray();
    for(int i=c.length-1;i>0;i--) {
    if(c[i]==' ') {
    for(int j=i+1;count>0;j++,count--) {
    System.out.print(c[j]);
    }
    System.out.print(" ");
    }
    else{
    count++;
    }
    }
    for(int j=0;count>=0;j++,count--) {
    System.out.print(c[j]);
    }
    }
    }

    ReplyDelete
  4. public class ReversePartOfString {
    public static void main(String[] args)
    {
    String str="My name is imran khan";
    char a[]=str.toCharArray();
    ReversePart(a);
    printArray(a);
    }

    private static void ReversePart(char[] a) {
    int start=0,end=0,i,j=0;

    for(i=0;i<a.length;i++)
    {
    start=i;

    while(a[i]!=' ' && i<a.length)
    { i++;
    }
    end = i;

    swapM(a,start,end);
    }

    }

    private static void printArray(char[] a) {
    int i=0;

    for(i=0;i<a.length;i++)
    {
    System.out.print(a[i]);
    }
    }

    private static void swapM(char[] a, int start, int end) {

    while(start<end)
    {
    char temp;
    temp=a[start];
    a[start]=a[end];
    a[end]=temp;
    }
    }
    }

    ReplyDelete
  5. This program is for reverse the word present in the given string
    input: my name is imran khan
    output:ym eman si narmi nahk

    ReplyDelete
  6. public String revRec(String str){
    if(!str.equals("")){
    if(str.indexOf(" ")!=-1){
    str = str.substring(str.lastIndexOf(" ")+1)+" "+revRec(str.substring(0, str.lastIndexOf(" ")));
    }
    }
    return str;
    }

    ReplyDelete
  7. public void revIter(String str){
    String[] arr = str.split(" ");
    Stack stack = new Stack();
    for(String s : arr) stack.push(s);
    for(int i=0; i<arr.length; i++) System.out.print(stack.pop()+" ");
    }

    ReplyDelete
  8. Your code doesn't reduce multiple spaces to a single space.

    ReplyDelete
  9. input:
    i love india
    output:
    i evol india

    is dis possible in java

    ReplyDelete
  10. i need code for this concept, anyone can help me

    input:
    i love india
    output:
    i evol india

    ReplyDelete
  11. Respected sir.,
    If my input is "watch this watch" & I want the output which is exactly same as input i.e. "watch this watch". How can I palindrome that string word-wise?

    ReplyDelete
  12. i need simple code for this concept
    input-This is my cat
    output-cat my is This
    plz help

    ReplyDelete