Write a program to Reverse Each Word of a String


This Java program reverses each word in a given string by splitting the string into individual words, reversing each word, and then concatenating the reversed words back into a new string. Here's a breakdown of how the program works:

  • The reverseEachWord() method is called with the input string "String and String function".
  • The input string is split into individual words using the split() method with the delimiter " ".
  • An empty string rev is declared to hold the reversed words.
  • A for loop is used to iterate over each word in the input string.
  • The reverseWithStringConcat() method is called with each word to reverse it.
  • The reversed word is concatenated with a space to the rev string using the + operator.
  • The display() method is called to print the input string and the reversed string.
  • The reversed string is returned by the reverseEachWord() method.

The reverseWithStringConcat() method takes a single string argument and returns the reversed string. It uses a for loop to iterate over the characters of the input string in reverse order, and concatenates them to an empty string rev_word using the + operator. The reversed string is returned by the method. The display() method takes two string arguments and prints them to the console.

Source Code

class Reverse_EachWord
{
	public static void main(String[] args)
	{
		reverseEachWord("String and String function");
	}
	private static String reverseEachWord(String str)
	{
		String[] words = str.split(" ");
		String rev = "";
		for (String word: words)
		{
			rev = rev + reverseWithStringConcat(word) + " ";
		}
		display(str, rev);
		return rev;
	}
	private static final String reverseWithStringConcat(String string)
	{
		String rev_word = "";
		for (int i = (string.length() - 1); i >= 0; i--)
		{
			rev_word = rev_word + string.charAt(i);
		}
		return rev_word;
	}
	private static final void display(String str, String rev)
	{
		System.out.println(str);
		System.out.println(rev);
	}
}

Output

String and String function
gnirtS dna gnirtS noitcnuf

Example Programs