Reverse words in string in Java

Learn to reverse each word in a sentence in Java with example. We will reverse words in string in place using StringBuilder and StringUtils classes.

Original String – how to do in java

Reverse words – woh ot od ni avaj

1. Reverse words in string – StringBuilder class

  • Tokenize each word using String.split() method.
  • Loop through string array and use StringBuilder.reverse() method to reverse each word.
  • Join all revered words to get back string.
String blogName = "how to do in java";
StringBuilder reverseString = new StringBuilder();

String[] words = blogName.split(" ");		//step 1

for (String word : words) 
{
    String reverseWord = new StringBuilder(word).reverse().toString();		//step 2
    reverseString.append(reverseWord + " ");								//step 3
}

System.out.println( reverseString.toString().trim() );		//verify reversed string

Program output.

woh ot od ni avaj

2. Reverse words in string – StringUtils class

StringUtils class is in Apache command lang library. Use it’s StringUtils.reverseDelimited() method to reverse each word and join the string.

String blogName = "how to do in java";

String reverseString = StringUtils.reverseDelimited( StringUtils.reverse(sentence), ' ' );

System.out.println( reverseString );

Program output.

woh ot od ni avaj

In this post, we learned to reverse each word in a sentence in Java.

Happy Learning !!

Leave a Reply

5 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions, and frequently asked interview questions.

Our Blogs

REST API Tutorial