Problem: - Write a Java program to reverse sentence by words.
Solution: - We are going to reverse the sentence by words. Let's take an example.Input: - "java code for solution"
Output: -"solution for code java".
Java code: -
Java code: -
package com.codeforsolution.java.logical;
public class ReverseSentenceByWords {
public static void main(String[] args) {
String input = "Today is a good day"; // expected output day good a is Today
System.out.println("reverse sentence:- "+reverseSentence(input));
}
public static String reverseSentence(String input) {
String reverseSentence = "";
String words[] = input.split(" ");
for(int i = words.length-1; i >=0; i--){
if(i==0)
reverseSentence= reverseSentence+ words[i];
else
reverseSentence= reverseSentence+ words[i]+" ";
}
return reverseSentence;
}}
Output: - reverse sentence:- day good a is Today