I am looking for way to reverse the order of words in a string in Kotlin.
For example, the input string would be:
What is up, Pal!
And the output string would be:
Pal! up, is What
I know I need to use the reversed module, but I am not sure how.
You are correct in assuming that the reversed
module would be helpful in this task.
However to reverse the order of the words you would also need to use things like split
and joinToString
(or implement them yourself):
fun reverseOrderOfWords(s: String) = s.split(" ").reversed().joinToString(" ")
val s = "What is up, Pal!"
println(reverseOrderOfWords(s))
Output:
Pal! up, is What
You could try this:
fun reverse(str:String) = str.split(" ").reduce{acc, x -> x + " " + acc}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With