Summary: In this programming example, we will learn different ways to reverse a given sentence word by word in Java.

Example:

The problem is to reverse a sentence without reversing its individual words.

We can solve this by extracting every word from the sentence and concatenate them in reverse order.

Here are two such ways to do so in Java:

Method 1: Using Loop

With the help of indexOf() and substring() methods, we extract the words from the input sentence and concatenate them to the reverse string in reverse order.

Output:

Enter a sentence: how are you
Reverse: you are how


Every time we append a word to the reverse string, we remove it from the input sentence.

We use the ‘while’ loop to repeat the process until no word in the input sentence is left to process.

Method 2: Using Recursion

What we did in the previous method can also be implemented using the recursion technique.

Output:

Enter a Sentence: Hello World!
Reverse: World! Hello


On each recursive call, we extract a word from the front of the sentence using str.substring(0, idx) and concatenate it to the reversed result (i.e., reverse(str.substring(idx+1))) in the reverse order.

The recursive call reverse(str.substring(idx+1)) passes the remaining sentence as an argument that in turn extracts the word from the front and concatenates it in reversed order.

These are the two methods using which we can reverse a sentence without reversing its individual words in Java programming language.

Leave a Reply

6 + 18 =