Coders Packet

A Java Program To Reverse A String Word by Word

By Vimmi Singh

It is a Java Program which reverses a string word by word. We will take input from the user and then reverse the obtained string word by word

import java.util.*; public class reverseStringWordbyWord { public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc=new Scanner(; String s=sc.nextLine(); String ans=""; for(int i=s.length()-1;i>=0;i--) { int k=i; while(i>=0 && s.charAt(i)!=' ') { i--; } ans= ans+s.substring(i+1,k+1); } System.out.println(" "+ ans); } }

1.First, we have taken a string input from the user.

2.Then we created an empty string that will store the result at the end.

3.Now we created a for loop which will traverse the string from the last character and assigned k=i.

4.Now while the index is greater than 0 and the character at index is not equal to space we will decrement the value of 'i' when space will come we will get out of the while loop and concatenate ans with the substring from i+1 to k+1.

5.For loop will keep doing this until it reaches the 0th index of the string. Then finally we will get out of the for loop and print the ans.



Input- This is a cow

Output- cow a is This

Download Complete Code


No comments yet