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 !!
Was this post helpful?
Let us know if you liked the post. That’s the only way we can improve.
ismail
How can I reverse 2 words in a string? For example reverse “Hi John” to “John Hi”.
Anton
// this is a little hard coded, you can’t use StringBuilder for this task
String original = “Hi John”;
String [] split = original.split(” “);
String result = split[1] + ” ” + split[0];
System.out.println(result);
Jagannathan
@Rishab
was this question is asked in amazon interview?
Rishabh Gupta
How can i reverse word of string without using any inbuilt function?
Mohan Das
store it in character array .Overwrite accordance with reversal using INDEX OF CHARACTERS
Here below is your program:-