Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse the order of words in a String in Kotlin

Tags:

string

kotlin

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.

like image 307
Patrick Star Avatar asked Jun 15 '17 23:06

Patrick Star


2 Answers

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
like image 94
Sash Sinha Avatar answered Oct 15 '22 14:10

Sash Sinha


You could try this:

fun reverse(str:String) = str.split(" ").reduce{acc, x -> x + " " + acc}

like image 31
Jun Avatar answered Oct 15 '22 14:10

Jun