Reverse words in a given String in Java

Java 8Object Oriented ProgrammingProgramming

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

 Live Demo

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);
raja
Published on 07-Dec-2018 06:54:56
Advertisements