Reverse Words In A String

Reverse Words In A String string

Given an input string, reverse the string word by word. For example, Given s = “the sky is blue”, return “blue is sky the”.

Reverse Words In A String Solution

public class ReverseWordsInAString {
    public String reverseWords(String s) {
        String[] words = s.trim().split("\\s+");
        String result = "";
        for(int i = words.length - 1; i > 0; i--) {
            result += words[i] + " ";
        }

        return result + words[0];
    }
}
Last modified October 4, 2020