5

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.

peterh
  • 11,875
  • 18
  • 85
  • 108
Patrick Star
  • 101
  • 2
  • 5

2 Answers2

17

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
Sash Sinha
  • 18,743
  • 3
  • 23
  • 40
3

You could try this:

fun reverse(str:String) = str.split(" ").reduce{acc, x -> x + " " + acc}
user2878850
  • 2,446
  • 1
  • 18
  • 22
Jun
  • 41
  • 3
  • fold could also work, for difference between fold and reduce, please see here: https://stackoverflow.com/questions/44429419/what-is-basic-difference-between-fold-and-reduce-in-kotlin-when-to-use-which – Jun Jun 26 '19 at 01:41