Monday, May 6, 2024

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
  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
    Replies
    1. public class ReverseWord {
      public static void main(String[] args) {
      String line = "watch this watch";
      String words[]=line.split("\\s");
      System.out.println(reverse(words, words.length-1));
      }

      private static String reverse(String[] split, int index) {
      if (split != null && index == 0)
      return String.valueOf(split[0]);
      return split[index] +" "+ reverse(split, index - 1);
      }
      }

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

    ReplyDelete
    Replies
    1. This comment has been removed by the author.

      Delete
    2. this is my new code
      package String;

      import java.util.Scanner;

      public class Rever {

      public static void main(String[] args) {
      // TODO Auto-generated method stub
      System.out.println("Enter any String");
      Scanner input = new Scanner(System.in);
      String word=" " +input.nextLine();

      int count=0;
      int length=0;
      for(int i=word.length()-1;i>=0;i--){
      count++;
      if(word.charAt(i) !=' ')
      {
      length++;
      }

      if(word.charAt(i)==' '||word.length()==count)
      {


      for(int j=i;j<=i+length;j++)
      {
      System.out.print(word.charAt(j));
      }

      length=0;

      }
      }

      }
      }


      Delete
    3. Beautiful code can u send me more string codes likes these one or please post here.. like finding substring in a string ...
      input : abchellodefghijkhello
      substring : hello
      output : hello - 2

      Delete
    4. can you explain the logic

      Delete
    5. public class Test12 {
      public static void main(String[] args) {
      String s = "This is my cat";
      String ar[] = s.split(" ");
      for (int i = ar.length - 1; i >= 0; i--) {
      System.out.print(" " + ar[i]);
      }

      }
      }

      Delete
    6. Nice, can you explain what your program is doing?

      Delete
  13. i want this programme in c language can anybody help me

    ReplyDelete
  14. Thanks You Vandana Mishra
    it helps me alot
    simple and easy logic

    ReplyDelete
  15. Method Testing#reverseWords doesn't reverse string. First of all this method reversed order of words using method Collections.reverse and after that outputed these words in reverse order also. So nothing changed. One of these operation is redundant

    ReplyDelete
  16. import java.util.*;
    public class ReverseLine {

    public static void main(String[] args) {
    // TODO Auto-generated method stub

    String str;
    Scanner sc = new Scanner(System.in);
    String finalStr = "";

    ArrayList result = new ArrayList<>();

    System.out.println("Enter a line of text");
    str = sc.nextLine();

    System.out.println(str);

    for(int i = 0; i < str.length(); i ++)
    {
    if(str.charAt(i) != ' ' || i == str.length() - 1)
    {
    finalStr = finalStr + str.charAt(i);
    }
    else if(str.charAt(i) == ' ' || i >= str.length())
    {
    result.add(finalStr);
    finalStr = "";
    }
    }
    result.add(finalStr);

    Collections.reverse(result);

    String[] strArray = result.toArray(new String[result.size()]);

    String finalStrr = "";

    for(int i = 0; i < strArray.length; i ++)
    {
    finalStrr = finalStrr + strArray[i] + " ";
    }

    System.out.println(finalStrr);

    }

    }

    ReplyDelete
  17. Reverse in place, no additional DS used :

    1) Sample text : " ram is costly"
    2) Reverse in-place the entire string : "yltsoc si mar"
    3) Now, reverse each word again : "costly is ram"

    Hope it helps

    ReplyDelete
  18. Sir,

    really interesting, all your tutorials. Just one remark - maybe instead of:
    String[] sa = line.trim().split("\\s");
    (reverseString method)
    better woudld be:
    String[] sa = line.split("\\s+"); ?

    Anyway - thank you for your very good job.

    1000.50.

    ReplyDelete
    Replies
    1. Yes, \\s can be replaced with \\s+ to make it greedy and solve the problem where words are separated from multiple spaces, but removing trim means you can have spaces before and after sentence which may result in empty string? isn't it?

      Delete
  19. Sir,

    It is an interesting question. I think you are right, though it is worth a small example.
    Let’s take a string: ” as sd df fg ”. ReverseString() method (without trim() and with \\s+) gives us an output:
    „fg df sd as”. It seems that spaces before and after sentence are removed. Really?
    Instead of : „sb.append(‘ ‘);” let’s try : „sb.append(’-‘);” The output is: ”fg-df-sd-as—” – at the end of our sentence we have two dashes. Using the trim() method the output is correct – one dash after each element of our string.

    Best

    1000.50.

    ReplyDelete
    Replies
    1. Yup, thanks for adding the example, makes it clear. Btw, what is 1000.50? why do you use that as signature?

      Delete
  20. sir, i have a string "My Name Is Sagar"
    and i want to reverse that string (without using array) in to "Sagar Is name My"
    can you suggest me the concept for reversing words of string without using array, or else the coding.

    Thanks

    ReplyDelete
  21. sir,
    i want to reverse words in string without using array.
    string is : my name is sagar
    reverse string is : sagar is name my
    can u suggest me the solution ?

    thank you

    ReplyDelete
    Replies
    1. Hello Akansha, use the StringBuilder as shown in first example

      Delete
  22. Hi sir,
    my String "abcdefghijklmn", in output screen i am entering the integer value 3,in output i want"cbafedihglkjomn".Any one can suggest me.


    Thanks

    ReplyDelete
    Replies
    1. Hi There,

      Greetings..!!

      Just Follow Bellow Basic Entry Level Code to Eliminate The Numbers From Given String To Print Only Characters

      import java.util.Scanner;

      public class ElemenateNumbersInString {
      public static void main(String[] args) {
      System.out.println("Enter Any String With Numbers");
      Scanner sc=new Scanner(System.in);
      String input=sc.nextLine();
      for(int i=0;i<input.length();i++) {
      if(Character.isDigit(input.charAt(i))) {
      continue;
      }
      System.out.print(input.charAt(i));
      }
      sc.close();
      }
      }

      Any Modifications and Suggestions Are Welcome..!!!

      Delete
  23. import java.util.Scanner;
    class Testing{
    public static void main(String []args){
    Scanner sc =new Scanner(System.in);
    String st= sc.nextLine();
    String []str=st.split(" ");
    for(int i=str.length-1;i>=0;i--){
    System.out.print(str[i]+" ");
    }
    }
    }

    ReplyDelete
  24. Hi All,
    The below code will eliminate the more iteration.

    public class ReverseAString {
    public static void main(String[] args) {
    String s1 = "Naveen";
    char[] charArray = s1.toLowerCase().toCharArray();
    int lastChar = charArray.length - 1;
    for (int first = 0; first < lastChar; first++, lastChar--) {
    char temp = charArray[first];
    charArray[first] = charArray[lastChar];
    charArray[lastChar] = temp;
    }
    System.out.println(new String(charArray));
    }
    }

    ReplyDelete
  25. input is : ram is a good boy
    output is : boy good a is ram

    Example 1 is not working means they didn't print any string
    send to me code my mail id : mukundagrawal1234@gmail.com

    ReplyDelete
  26. I Needed the program
    Get a string from the user. For each character in the string, if the character is lower case then replace it with the next letter in the alphabet. If the character is in upper case, replace it with the previous letter in the alphabet.

    For example. if input string is PeT, then the output string should be "oFs"
    send me the code to kiranskumar95@gmail.com

    ReplyDelete
    Replies
    1. import java.util.*;
      public class Main
      {
      public static void main(String[] args) {
      System.out.println("Hello World");
      String str = "HEllo";
      char ch[] = str.toCharArray();
      for(int i=0; i=65 && asciivalue<=91)
      {
      asciivalue = asciivalue-1;
      char c = (char)asciivalue;
      char C= c;
      System.out.print(C);
      }
      else
      {
      asciivalue = asciivalue+1;
      char c1 = (char)asciivalue;
      char C1 = c1;
      System.out.print(C1);
      }
      }
      }
      }

      Delete
  27. class ReverseString
    {
    public static void main(String s[])
    {
    String org ="My name is Ritu";
    String rev ="";
    int b;
    int l = org.length();
    for(int i=org.length()-1;i>=0;i--)
    {
    if(org.charAt(i)==' ')
    {
    b=i+1;
    rev += org.substring(b,l)+" ";
    l=i;
    }
    else if(i==0)
    {
    rev += org.substring(0,l);
    }
    }
    System.out.print("Reverse:: "+rev);
    }
    }

    ReplyDelete
  28. //Input String="This String will be getting reversed";
    //Output String="sihT gnirtS lliw eb gnitteg desrever";
    public class StringReverse {

    public static void main(String[] args) {

    String word = "This String will be getting reversed";
    String reversedWord="";
    String[] words= word.split(" ");

    for(int i=0; i=0;j--){
    System.out.print(c[j]);
    }
    System.out.print(" ");
    }


    }

    }

    ReplyDelete
  29. I have String AbcDef and I want to shift f in beginning and than i want to shift De in beginning can anyone help me to find that program?

    ReplyDelete
    Replies
    1. It's called rotation, In order to rotate you need a rotation point, and rotate to right or left and for how many character

      Delete
  30. @javin paul

    it seems like your first solution (with ArrayList) is reversing the sentence with collections.reverse() and then reversing it again (back to the original) by starting the for loop at the end of the array instead of at the beginning.

    Very interesting tutorials by the way. This helps me a lot!!

    ReplyDelete
  31. input-> This boy is very good
    output->doog sihT yrev yob is

    please solve.

    ReplyDelete
    Replies
    1. You need to reverse both words in the sentence and word as well. So just combine the solution give in this article as well on how to reverse string in Java and you will have your solution .

      Delete
  32. public class reverse{

    public static void main (String[] args){

    String s1 = "my name is pankaj";

    String[] arr = s1.split(" ");
    int len = arr.length;
    String[] temp = new String[len];


    for(int i=0; i=0; j--){
    s2 = s2+ c[j];

    }
    temp[i] = s2;

    }

    for (int i =0; i<arr.length; i++){

    System.out.print(temp[i] + " ");
    }



    }
    }

    ReplyDelete

Feel free to comment, ask questions if you have any doubt.