How to Reverse a String in Java word by word

How to Reverse a String in Java word by word

Here you will learn how to reverse a string in java word by word. This java program to reverse words of a string is very simple using the Regex Pattern.

This program will reverse each word of a string and will display the reversed string as an output.

Below are the steps to be followed:

  • Find the pattern/split with space.
  • Reverse the order with loop
How to Reverse a String in Java word by word

Example:

Input : “I love TechBlogStation”
Output :”TechBlogStation love I”
//Java Program to reverse a String 
import java.util.regex.Pattern; 
public class ReverseString { 

	// Reverse words of a String 
	static String reverseWords(String str) 
	{ 

		//pattern to be looked for 
		Pattern pattern = Pattern.compile("\\s"); 

		// splitting String with a pattern 
		String[] temp = pattern.split(str); 
		String result = ""; 

		// the string in reverse order. 
		for (int i = 0; i < temp.length; i++) { 
			if (i == temp.length - 1) 
				result = temp[i] + result; 
			else
				result = " " + temp[i] + result; 
		} 
		return result; 
	} 

	 
	public static void main(String[] args) 
	{ 
		String s1 = "I love TechBlogStation"; 
		System.out.println(reverseWords(s1)); 

	} 
} 

Conclusion

In this post, you have learned how to reverse each word in a sentence using Java.

Leave a Reply

Your email address will not be published. Required fields are marked *