- 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
Reverse words in a given String in Java
The order of the words in a string can be reversed and the string displayed with the words in reverse order. An example of this is given as follows.
String = I love mangoes Reversed string = mangoes love I
A program that demonstrates this is given as follows.
Example
import java.util.regex.Pattern; public class Example { public static void main(String[] args) { String str = "the sky is blue"; Pattern p = Pattern.compile("\s"); System.out.println("The original string is: " + str); String[] temp = p.split(str); String rev = ""; for (int i = 0; i < temp.length; i++) { if (i == temp.length - 1) rev = temp[i] + rev; else rev = " " + temp[i] + rev; } System.out.println("The reversed string is: " + rev); } }
Output
The original string is: the sky is blue The reversed string is: blue is sky the
Now let us understand the above program.
First the original string is printed. The the string is split when there is whitespace characters and stored in array temp. The code snippet that demonstrates this is given as follows.
String str = "the sky is blue"; Pattern p = Pattern.compile("\s"); System.out.println("The original string is: " + str); String[] temp = p.split(str); String rev = "";
Then a for loop is used to store the string in reverse order in string rev by iterating over the string temp. Finally rev is displayed. The code snippet that demonstrates this is given as follows −
for (int i = 0; i < temp.length; i++) { if (i == temp.length - 1) rev = temp[i] + rev; else rev = " " + temp[i] + rev; } System.out.println("The reversed string is: " + rev);
Advertisements