How to Reverse words in String Java? [Solution]

Hello guys, if you are wondering how to reverse words in a given String in Java then you have come to the right place. Earlier, I have shared 75 Programming interview questions and 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 that contains the word in reverse order, for example, if the 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 Interviewer. Never assume you know everything, even if it looks like 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 the 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 like 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 the 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.





Reversing the order of words in a Sentence in Java - Solution

Here is our Java solution to this problem. It's simple and straightforward.  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 into spaces and then using the 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 an 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 the creation of a new array and copying content from the old to the new array.

As I said earlier, for more coding problems from programming interviews, you can also check the Grokking the Coding Interview: Patterns for Coding Questions, one of the best resources to learn essential coding patterns like sliding window, merge interval, fast and slow pointers, etc which can be used to solve 100+ Leetcode problems. 

How to Reverse words in String Java



The second method to reverse words in a given string is, even more, easier, instead of using the Collections.reverse() method, I have just used the traditional for loop and started looping over array from the 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 the 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 like 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();
   }
 }
}


Sometimes Interviewer may ask you to solve this problem without using the Java Collection framework because it obviously makes the task a lot easier. So it's also good to prepare a solution based upon pure programming logic. 

If you know how to reverse an array in Java, then you have an advantage because String is nothing but a character array, but the tricky part is you don't need to reverse array but to reverse words.

And, If you are preparing for a programming interview, I also suggest taking a look at Cracking the Coding Interview: 189 Programming Questions and Solutions, one of the best books to prepare for programming job interviews. You will find several such problems and great explanations in this book.

how to reverse all words in given String


That's all about how to reverse words in a String sentence in Java. You have learned two ways to reverse the order of words. You have also learned how to split String using regex, which is an important skill for Java programmers and you have also learned a good utility method to reverse any Collection in Java. It's good to practice this kind of coding problem both to learn Java and to improve your programming and coding skills.



Other Java Coding Problems You may like to Practice
  • 100+ Data Structure and Algorithms Problems (solutions)
  • Write a program to print the highest frequency word from a text file? (solution)
  • How to find if given String is a palindrome in Java? (solution)
  • How to calculate factorial using recursion and iteration? (solution)
  • How to reverse an integer variable in Java? (solution)
  • Write code to implement Bubble sort algorithm in Java? (code)
  • How to find the highest and lowest number from the int array? (answer)
  • How do you swap two integers without using a temporary variable? (solution)
  • Top 10 Programming problems from Java Interviews? (article)
  • Write a program to check if a number is the power of two or not? (solution)
  • How to check if a year is a leap year in Java? (answer)
  • How to check if a given number is prime or not? (solution)
  • How to reverse String in Java without using StringBuffer? (solution)
  • Write code to implement Quicksort algorithm in Java? (algorithm)
  • How to find a missing number in a sorted array? (solution)
  • Write a program to code insertion sort algorithm in Java (program)

Thanks for reading this article so far. If you like this String based coding problem and solution then please share it with your friends and colleagues. If you have any doubt then please drop a note.

P. S. - If you are a beginner and looking for some Free Algorithms courses to improve your understanding of Data Structure and Algorithms, then you should also check the Data Structure in Java free course on Udemy. It's completely free and all you need to do is create a free Udemy account to enroll in this course.

63 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. With an abusive amount of string objects being created over the iteration, although it does the job, it's far from memory efficient

      Delete
    3. One More Simplest:
      package inTerview;
      import java.util.*;

      public class ReverseText {
      public static void main(String[] args) {

      String name="This String will be getting reversed";
      System.out.println("Original Name: "+name);
      System.out.println("After Reverse: ");
      for(int i=name.length()-1; i>=0; i--)
      {
      System.out.print(name.charAt(i));
      }
      }
      }

      Output:
      Original Name: This String will be getting reversed
      After Reverse:
      desrever gnitteg eb lliw gnirtS sihT

      Delete
    4. thank you very much

      Delete
    5. reverse only words at the same place like --> This is me --> sihT si em

      Delete
    6. public class Reverse_words_of_a_sentence {

      public static void main(String[] args)
      {
      String rev = "This is Akash Aggarwal";
      int veg=0;
      rev = rev+" ";

      // for(int i=rev.length()-1;i>=0;i--)
      // {
      // System.out.print(rev.charAt(i)); // reverse string without hold place
      // }

      for(int i=0;i=veg;j--)
      {
      System.out.print(rev.charAt(j)); // revers string with hold posation
      }
      veg=i+1;
      }
      }
      }

      }


      input : This is Akash Aggarwal
      output : sihT si hsakA lawraggA

      Delete
    7. class ReverseWord
      {
      public static void main(String[] args)
      {
      String s[]="my name is maddy".split("\\s");
      String rev="";
      for(int i =s.length-1;i>0;i--)
      {
      rev=rev+s[i]+"";
      }
      System.out.println(rev);
      }
      }

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

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

    ReplyDelete
    Replies
    1. package String;

      public class reversestring {

      public static void main(String[] args) {
      // TODO Auto-generated method stub
      int count=0;
      String out=new String();
      String input ="the world is awsome ";
      //put space end of the String input
      // emo swasi dl roweht

      //for space remove
      for(int x=0;x<input.length();x++)
      {
      if(input.charAt(x)!=' ')
      {
      out+=Character.toString(input.charAt(x));
      }
      }

      int length=out.length()-1;
      for(int i=0;i<input.length();i++)
      {
      if(input.charAt(i)!=' ')
      {
      count++;
      }
      if(input.charAt(i)==' ')
      {
      for(int j=0;j<count;j++)
      {
      System.out.print(out.charAt(length));
      length--;
      }
      count=0;
      System.out.print(" ");
      }


      }

      }

      Delete
    2. reverse(String s)
      {
      int l=s.length();
      char t;
      for(int i=0;i<l/2;i++)
      {
      t=s.charAt(i);
      s.charAt(i)=s.charAt(l);
      s.charAt(l)=i;
      }

      }

      Delete
    3. public static void main(String[] args) {
      // TODO Auto-generated method stub
      String line = "the world is awsome";
      System.out.println("the world is awsome : \n" + reverseWord(line));
      }

      static String reverseWord(String line) {
      String noSpaceLine = line.replace(" ", "");
      int noSpaceLength = noSpaceLine.length()-1;

      int length = line.length();
      StringBuilder sb = new StringBuilder(line.length());
      for(int i=0; i<=length-1; i++) {
      if(line.charAt(i)!=' ') {
      sb.append(noSpaceLine.charAt(noSpaceLength));
      noSpaceLength--;
      } else
      sb.append(' ');
      }
      return sb.toString().trim();
      }

      Delete
    4. public static void main(String[] args) {
      // TODO Auto-generated method stub
      String line = "the world is awsome";
      System.out.println("the world is awsome : \n" + reverseWord(line));
      }

      static String reverseWord(String line) {
      String noSpaceLine = line.replace(" ", "");
      int noSpaceLength = noSpaceLine.length()-1;

      int length = line.length();
      StringBuilder sb = new StringBuilder(line.length());
      for(int i=0; i<=length-1; i++) {
      if(line.charAt(i)!=' ') {
      sb.append(noSpaceLine.charAt(noSpaceLength));
      noSpaceLength--;
      } else
      sb.append(' ');
      }
      return sb.toString().trim();
      }

      Delete
  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
    Replies
    1. public static void main(String[] args) {

      String s = "I love India";
      List list = new ArrayList();
      String [] str = s.split(" ");
      for(int i=0;i=0;j--) {
      r = r + str[i].charAt(j);
      }
      list.add(r);
      }
      list.add(str[str.length-1]);
      for(int i=0;i<list.size();i++) {
      System.out.print(list.get(i)+" ");
      }
      }

      Delete
    2. public static void main(String[] args) {

      String s = "I love India";
      List list = new ArrayList();
      String [] str = s.split(" ");
      for(int i=0;i=0;j--) {
      r = r + str[i].charAt(j);
      }
      list.add(r);
      }
      list.add(str[str.length-1]);
      for(int i=0;i<list.size();i++) {
      System.out.print(list.get(i)+" ");
      }
      }

      Delete