Summary: In this programming example, we will learn different ways to reverse a given sentence word by word in Java.
Example:
Input: I am a programmer Output: programmer a am I
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.
import java.util.Scanner;
public class Main {
public static void main(String args[]){
Scanner in =new Scanner(System.in);
//Input sentence
System.out.print("Enter a sentence: ");
String str = in.nextLine();
//Append whitespace for the extraction of last word
str += " ";
String reversed = "";
//repeat until no word is left
while(str.indexOf(" ") != -1){
//Extract word
int idx = str.indexOf(" ");
String word = str.substring(0, idx);
//Concatenate in reverse order
reversed = word + " "+ reversed;
//Remove word from the sentence
str = str.substring(idx+1);
}
//Output the reverse
System.out.print("Reverse: ");
System.out.println(reversed);
}
}
Output:
Enter a sentence: how are youReverse: 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.
import java.util.Scanner;
public class Main {
public static void main(String args[]){
Scanner in =new Scanner(System.in);
//Input sentence
System.out.print("Enter a Sentence: ");
String sentence = in.nextLine();
//Reverse by calling the recursive method
String reversed = reverse(sentence);
//output the reversed word
System.out.print("Reverse: ");
System.out.println(reversed);
}
public static String reverse(String str){
int idx = str.indexOf(" ");
//Base condition - when str has only one word
if(idx == -1)
return str;
//return after concatenating in reverse order
return reverse(str.substring(idx+1)) +" "+ str.substring(0, idx);
}
}
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.