Reverse Words in String
Reverse Words in String
Reverse Words in String
Problem Statement:
Given a string containing words separated by spaces, reverse the order of the words and return the final string.
Input Example:
s = "the sky is blue"Output Example:
blue is sky the
Solution:
fun main() {
val s = " the sky is blue "
val words = s.trim().split(Regex("\\s+"))
val reversedString = StringBuilder()
for (i in words.size - 1 downTo 0) {
reversedString.append(words[i])
if (i != 0) {
reversedString.append(" ")
}
}
print(reversedString.toString())
}