JAVA String - Reverse Words [ZOHO]
A string S is passed as the input. The program must reverse the order of the words in the string and print them as the output.
Input Format:
The first line will contain S.
Output Format:
The first line will contain the words in the string S in the reverse order.
Boundary Conditions:
Length of S is from 5 to 100.
Example Input/Output 1:
Input:
Today is Friday
Output:
Friday is Today
Example Input/Output 2:
Input:
five six ten eleven
Output:
eleven ten six five
Java Program:
import java.util.*;
public class Hello {
public static String reverseWords(String s) {
if (s == null || s.length() == 0) {
return "";
}
String[] arr = s.split(" ");
StringBuilder sb = new StringBuilder();
for (int i = arr.length - 1; i >= 0; --i) {
if (!arr[i].equals("")) {
sb.append(arr[i]).append(" ");
}
}
return sb.length() == 0 ? "" : sb.substring(0, sb.length() - 1);
}
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
String s=sc.nextLine();
System.out.println(reverseWords(s));
}
}
Comments
Post a Comment