Reverse Each Word in a Sentence in Java



Given a sentence or string, write a Java program to reverse each word in that sentence. Each word in that sentence should be reversed and at the same time, they should be in the same order as before.

Let's understand the problem with an example ?

Example Scenario:

Input: orgnl_sen = an apple is red
Output: modfd_sen = na elppa si der

Using Iteration

First, split the given sentence into an array of words using the space character as the delimiter. Use a for-each loop to iterate over each word. Then, iterate through the characters of each word in reverse order, and append the characters to a new string.

Example

The following Java program explains how to reverse each word in a sentence.

public class Example {
   public static void main(String[] args) {
      String str = "Simply Easy Learning";
      System.out.println("The original string is: " + str);
      String strWords[] = str.split("\s");
      // variable to store the reversed sentence
      String rev = "";
      for (String sw : strWords) {
         // variable to store the reverse word
         String reverseWord = "";
         for (int i = sw.length() - 1; i >= 0; i--) {
            reverseWord += sw.charAt(i);
         }
         // joining the reversed word 
         rev += reverseWord + " ";
      }
      System.out.println("The modified string is: " + rev.trim());
   }
}

When you execute the above code, it will display the following output ?

The original string is: Simply Easy Learning
The modified string is: ylpmiS ysaE gninraeL

Using reverse() Method

In this approach, divide the words using split() method and store all the words in an array. Then, reverse all the words using reverse() method and append it to a StringBuilder object.

Example

Let's see the practical implementation in the below Java program ?

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());
   }
}

On running this code, you will get the following result ?

The original string is: the sky is blue
The modified string is: eht yks si eulb
Updated on: 2024-09-25T18:27:47+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements