Word Reverse Program

How To Reverse The Order Of  Words In A Given Input String.

Input: "My name is Darga "

Output: "Darga is name My"

package praticeprogrms2;

public class WordReverse

{

    public static void main(String[] args)

    {

        String input = "My name is Darga";

        String output = reverseWords(input);

        System.out.println("Input : " +input);

        System.out.println("Output : " +output);

    }

    public static String reverseWords(String input)

    {

        String[] words = input.split(" "); // Split the input string into words

        StringBuilder reversed = new StringBuilder();

        for (int i = words.length - 1; i >= 0; i--)

        {

            reversed.append(words[i]).append(" "); // Append words in reverse order

        }

        return reversed.toString().trim(); // Remove the trailing space and return the result

    }

}

Output :

Input : My name is Darga

Output : Darga is name My

Explanation:

  1. The reverseWords function takes the input string as a parameter.
  2. It uses the split method to break the input string into an array of words, splitting at each space.
  3. A StringBuilder named reversed is used to build the reversed word order.
  4. A loop runs through the array of words in reverse order (from the last word to the first).
  5. Each word is appended to the reversed StringBuilder, followed by a space.
  6. Finally, the trim method is called to remove the trailing space, and the reversed string is returned.

Comments

Popular posts from this blog

Installing MySQL and MySQL Workbench

Java Program to Check Palindrome Number

Scenario : 1