Write a program to reverse words in a given string


The program starts by defining a static method reverse_word() that accepts a string parameter str. It creates a StringBuilder object rv from the input string str, reverses it using the reverse() method, and converts it back to a string rev.

Then, it splits the reversed string into individual words using the split() method with space as a delimiter and initializes a new StringBuilder reverse. It iterates through each word using a for-each loop, creates a new StringBuilder rv from the word, reverses it using the reverse() method, and appends it to the reverse StringBuilder with a space.

After iterating through all the words, it deletes the last space character using the deleteCharAt() method and returns the resulting string as a string using the toString() method.

The program also defines a main() method that initializes a string variable str with the value "Tutor Joes Computer Education", prints the original string to the console, calls the reverse_word() method to reverse the words in the string, and prints the result to the console.

Source Code

class Reverse_word
{
	public static String reverse_word(String str)
	{
		StringBuilder rv = new StringBuilder(str);
		String rev = rv.reverse().toString();
 
		String[] words = rev.split(" ");
		StringBuilder reverse = new StringBuilder();
		for (String w: words)
		{
			rv = new StringBuilder(w);
			reverse.append(rv.reverse() + " ");
		}
		reverse.deleteCharAt(reverse.length() - 1);
		return reverse.toString();
	}
	public static void main(String[] args)
	{
		String str = "Tutor Joes Computer Education";
		System.out.println("Given String : " + str);
		System.out.println("Reversed Words in String : " + reverse_word(str));
	}
}

Output

Given String : Tutor Joes Computer Education
Reversed Words in String : Education Computer Joes Tutor

Example Programs