Given an input string, reverse the string word by word.
Example 1:
Example 2:
Example 2:
Solution
We can use Space as a tokenizer to split the string, Iterate array from end element and accumulate none empty string to the result string.
Code
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
public class ReverseWords { public static void main(String[] args) { String s="the sky is blue"; System.out.println(new ReverseWords().reverseWords(s)); } public String reverseWords(String s) { s=s.trim(); // Triming will take care tailing space. String sArr [] =s.split(" "); //Split with Space. String result=""; for(int i=sArr.length-1;i>=0;i--){ if(!sArr[i].trim().equals("")){ result+=sArr[i]+" "; } } return result.trim(); } } |
Output
We encourage you to write a comment if you have a better solution or having any doubt on the above topic.