Reverse a string in java word by word

Let’s learn to reverse a string in java word by word.

Reverse a string in java word by word

To reverse a string word by word first get input from user using nextLine() method of scanner class.

This user entered string is stored in String variable ‘strGiven’.

Then this string variable is converted to character array using toCharArray() method of class String.

In the next step two for loops is used. First for loop iterates variable ‘a’ from 0 to a < length of given character array.

Then if chArray[a] != ‘ ‘ add chArray[0] to string strWord.

Next until we get space, if block adds characters to String variable ‘strWord’.

Moving on, else block reverses the word if we get space. Lastly second for loop reverses last word.

Here’s program to reverse a string word by word.

import java.util.Scanner;
public class ReverseStringWordByWord 
{
   public static void main(String[] args) 
   {
      String strWord = "";
      Scanner sc = new Scanner(System.in);
      System.out.println("Please enter a string: ");
      String strGiven = sc.nextLine();     
      char[] chArray = strGiven.toCharArray();
      System.out.println("Reversed string word by word: ");
      for(int a = 0; a < (chArray.length); a++)
      {
         if(chArray[a] != ' ')
         {
            strWord = strWord + chArray[a];
         }
         else
         {
            for(int b = strWord.length(); b > 0; b--)
            {
               System.out.println(strWord.charAt(b - 1));       
            }
            System.out.print(" ");
            strWord = "";
         }
      }
      for(int b = strWord.length(); b > 0; b--)
      {
         System.out.println(strWord.charAt(b - 1));       
      }
      sc.close();
   }
}


Output:

Please enter a string: hello world java
Reversed string word by word: olleh dlrow avaj

Please enter a string: flower brackets java
Reversed string word by word: rewolf stekcarb avaj