- Trending Categories
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());
- Related Articles
- Python program to reverse each word in a sentence?
- Write a java program to reverse each word in string?
- Java program to count the characters in each word in a given sentence
- Java Program to Reverse a Sentence Using Recursion
- Write a java program reverse tOGGLE each word in the string?
- Java Program to replace a word with asterisks in a sentence
- C++ program to Reverse a Sentence Using Recursion
- Haskell Program to Reverse a Sentence Using Recursion
- Golang Program to Reverse a Sentence using Recursion
- Python program to find the smallest word in a sentence
- Program to reverse the position of each word of a given string in Python
- Reverse each word in a linked list Node
- Python Program to replace a word with asterisks in a sentence
- Write a java program to tOGGLE each word in string?
- PHP program to find the first word of a sentence

Advertisements