1// Reverse a string in java word by word
2import java.util.Scanner;
3public class ReverseStringWordByWord
4{
5 public static void main(String[] args)
6 {
7 String strWord = "";
8 Scanner sc = new Scanner(System.in);
9 System.out.println("Please enter a string: ");
10 String strGiven = sc.nextLine();
11 char[] chArray = strGiven.toCharArray();
12 System.out.println("Reversed string word by word: ");
13 for(int a = 0; a < (chArray.length); a++)
14 {
15 if(chArray[a] != ' ')
16 {
17 strWord = strWord + chArray[a];
18 }
19 else
20 {
21 for(int b = strWord.length(); b > 0; b--)
22 {
23 System.out.println(strWord.charAt(b - 1));
24 }
25 System.out.print(" ");
26 strWord = "";
27 }
28 }
29 for(int b = strWord.length(); b > 0; b--)
30 {
31 System.out.println(strWord.charAt(b - 1));
32 }
33 sc.close();
34 }
35}