Friday 24 May 2019

Java: Reverse words in a sentence


Reverse the words in a sentence.

For example, for the string "Hello, How are you", the output should be "you are How, Hello"

Below function reverse the words in a string.

public static String reverseWordsInSentence(String sentence) {
         if (sentence == null || sentence.isEmpty()) {
                  return sentence;
         }

         String[] words = sentence.split("\\b");
         int length = words.length - 1;

         StringBuilder builder = new StringBuilder();

         for (int i = length; i >= 0; i--) {
                  builder.append(words[i]);
         }

         return builder.toString();

}

App.java
package com.sample.app;

import java.io.IOException;

public class App {

 public static String reverseWordsInSentence(String sentence) {
  if (sentence == null || sentence.isEmpty()) {
   return sentence;
  }

  String[] words = sentence.split("\\b");
  int length = words.length - 1;

  StringBuilder builder = new StringBuilder();

  for (int i = length; i >= 0; i--) {
   builder.append(words[i]);
  }

  return builder.toString();

 }

 public static void main(String args[]) throws IOException {

  String str = "Hello, How are you";

  System.out.println("str : " + str);
  System.out.println("reverse : " + reverseWordsInSentence(str));
 }
}

Output
str : Hello, How are you
reverse : you are How, Hello


You may like

No comments:

Post a Comment