How to Reverse a String in Java Word by Word

In this section, we reverse a string in Java word by word.

Example 1: Reverse a string word by word using recursion

  1. import java.util.Scanner;  
  2. public class ReverseStringExample1   
  3. {  
  4. public static void main(String[] args)   
  5. {  
  6. String str;  
  7. System.out.println(“Enter a string: “);  
  8. Scanner scanner = new Scanner(System.in);  
  9. str = scanner.nextLine();  
  10. scanner.close();                                //closes the input stream  
  11. String reversed = reverseString(str);  
  12. System.out.println(“The reversed string is: ” + reversed);  
  13. }  
  14. public static String reverseString(String s)  
  15. {  
  16. if (s.isEmpty())                            //checks the string if empty  
  17. return s;  
  18. return reverseString(s.substring(1)) + s.charAt(0);                     //recursively called function  
  19. }  
  20. }  

Output:

How to Reverse a String in Java Word by Word

Example 2: Reverse a string word by word by using for loop

  1. import java.util.*;  
  2. public class ReverseStringDemo  
  3. {  
  4. public static void main(String[] arg)  
  5. {  
  6. ReverseStringDemo rs=new ReverseStringDemo();  
  7. Scanner sc=new Scanner(System.in);  
  8. System.out.print(“Enter a string: “);  
  9. String  str=sc.nextLine();    
  10. System.out.println(“Reverse of a String  is : “+rs.reversestr(str));          //called method  
  11. }  
  12. //reverse string method  
  13. static String reversestr(String s)  
  14. {  
  15. String r=””;  
  16. for(int i=s.length();i>0;–i)        //execute until condition i>0 becomes false  
  17. {  
  18. r=r+(s.charAt(i-1));   
  19. }  
  20. return r;  
  21. }  
  22. }  

Output:

How to Reverse a String in Java Word by Word

Leave a Comment