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 passed as parameter to strReverse() method.

In strReverse() method for loop is executed until for(int a = str.length(); a > 0; –a) become false.

import java.util.Scanner;
public class ReverseWordByWord 
{
   public static void main(String[] args) 
   {
      Scanner sc = new Scanner(System.in);  
      System.out.print("Please enter string to reverse: ");  
      String strGiven = sc.nextLine();    
      System.out.println("After reversing string : " + strReverse(strGiven));
      sc.close();
   }
   static String strReverse(String str)
   {
      String reverse = "";  
      for(int a = str.length(); a > 0; --a)  
      {
         reverse = reverse + (str.charAt(a - 1));
      }
      return reverse;
   }
}


Output:

Please enter string to reverse: hello world java
After reversing string : avaj dlrow olleh


Now let’s reverse a string word by word using recursion.

import java.util.Scanner;
public class ReverseStringUsingRecursion
{
   public static void main(String[] args)
   {
      String strInput;
      Scanner sc = new Scanner(System.in);
      System.out.println("Please enter string: ");  
      strInput = sc.nextLine();  
      String strReversed = strReverse(strInput);  
      System.out.println("Reversed string is: " + strReversed);
      sc.close();
   }
   public static String strReverse(String str)
   {
      if(str.isEmpty())
         return str;
      return strReverse(str.substring(1)) + str.charAt(0);  
   }
}


Output:

Please enter string: I love coding
Reversed string is: gnidoc evol I