Java program to reverse each word in a sentence

Java 8Object Oriented ProgrammingProgramming

Each word in a sentence can be reversed and the sentence displayed with the words in the same order as before. An example of this is given as follows −

Original sentence = an apple is red
Modified sentence = na elppa si der

A program that demonstrates this is given as follows.

Example

 Live Demo

public class Example {
public static void main(String[] args) {
String str = "the sky is blue";
System.out.println("The original string is: " + str);
String strWords[] = str.split("\\s");
String rev = "";
for(String sw : strWords) {
StringBuilder sb = new StringBuilder(sw);
sb.reverse();
rev += sb.toString() + " ";
}
System.out.println("The modified string is: " + rev.trim());
}
}

Output

The original string is: the sky is blue
The modified string is: eht yks si eulb

Now let us understand the above program.

First, the original string is displayed. Then split() method is used to store all the words in array strWords[]. The code snippet that demonstrates this is given as follows −

System.out.println("The original string is: " + str);
String strWords[] = str.split("\\s");

The string rev contains all the words after they are reversed. This is done by using the reverse() method in for loop. Then rev is displayed. The code snippet that demonstrates this is given as follows −

String rev = "";
for(String sw : strWords) {
StringBuilder sb = new StringBuilder(sw);
sb.reverse();
rev += sb.toString() + " ";
}
System.out.println("The modified string is: " + rev.trim());
raja
Published on 06-Dec-2018 11:37:52
Advertisements