- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Java program to reverse each word in a sentence
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
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());
Advertisements