Home > Software design >  Write a program in Java to enter a String and display the words in reverse order
Write a program in Java to enter a String and display the words in reverse order

Time:12-31

Sample Input : Computer is Fun

Sample Output : Fun is Computer

I am not getting any idea that where to start from. Please help me out with the program.

CodePudding user response:

Use .split("\\s") to split the string on each space and put the words on a stack. Then reverse the process by reading from the stack and adding a space after each word.

CodePudding user response:

Think of this "Sample Input" string as a string array, and then output the array in reverse order。

public void Test() {
    String SampleInput="Computer is Fun";
    String[] split = SampleInput.split(" ");
    for (int i=split.length-1;i>=0;i--){
        System.out.print(split[i] " ");
    }
}
  • Related