Reverse Words In a String Java

Reverse Words In A String Java | Previously we have seen different approaches to reverse a string in Java programming. Now let us see how to reverse words in a string in Java. 

In a given sentence or string, the words are separated by whitespaces like tab, space, and e.t.c. To reverse each word in a given string we can take help from the StringBuilder class. The StringBuilder class contains a reverse() method which is used to reverse the given string value.

On reversing the words in a given string, the position of the words won’t be changed instead the position of each character in a word will be changed. Let us understand it through an example. Example:- 

String: Hi, How are You?
After reversing the words: ,iH woH era ?uoY

Program to Reverse Words In a String Java

public class Main {
   public static String reverseWords(String string) {
      String words[] = string.split("\\s");
      String reverse = "";
      for (String word : words) {
         StringBuilder sb = new StringBuilder(word);
         sb.reverse();
         reverse += sb.toString() + " ";
      }
      return reverse.trim();
   }

   public static void main(String[] args) {
      String string = "Welcome to Know Program";
      System.out.println("String: " + string);
      System.out.println("After reversing the words: " 
                         + reverseWords(string));
   }
}

Output:-

String: Welcome to Know Program
After reversing the words: emocleW ot wonK margorP

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published. Required fields are marked *