Java Programs

TheFestFever.com

Our aim is to connect students from campuses all over Delhi by making them aware of all Technical, Cultural, Management fests, workshops, Seminars organized by every college in Delhi.

Join Us Now

Program 43: Write a Java program to reverse each word of a string.

Reverse.java

import java.util.Scanner;

public class Reverse
{
	//Method to reverse each word of a string.
	public static String reverseEachWord(String input)
	{
		int i;
		int count=0;
		String str="";

		for(i=0; i < input.length();i++)
		{
			if(input.charAt(i)==' ')
			{
				for(int j=i-1;j>=count;j--)
				{
					str+=input.charAt(j);
				}
				count=i+1;
				str+=" ";
			}

			//reversing last word
			if(i==input.length()-1)
			{
				for(int j=i;j>=count;j--)
				{
					str+=input.charAt(j);
				}
			}
		}
        return str;
	}
	
	//Main method
	public static void main(String[] args)
	{
		Scanner s = new Scanner(System.in);
		System.out.println("Enter the string");
		String input = s.nextLine();

		System.out.println("Changed String");
		System.out.println(Reverse.reverseEachWord(input));
	}
}



If you have any suggestion or found any error in the above program, then do let us know at [email protected] or just comment below.