Zimri Leisher
01/20/2021, 2:12 AMval words = input.split(" ").map { it.trim() }
?ephemient
01/20/2021, 2:14 AMZimri Leisher
01/20/2021, 2:26 AMAnimesh Sahu
01/20/2021, 4:07 AMinput.split(" ") { it.trim() }
joinToString
actually...nanodeath
01/20/2021, 5:08 AMsplitToSequence
here, avoid that extra list allocation. input.splitToSequence(" ").map { it.trim() }.toList
. also...trim
removes all whitespace, not just the space character, so strictly speaking it's not redundant. depends on whether you're expecting \t
and friends to show up.Ahmed Mourad
01/20/2021, 5:49 AMsplit
also accepts a regex so you could do
input.split(Regex("\\s+"))
which makes the trimming step unnecessary, and also prevents having empty string entries when you have three or more consecutive whitespaces.Zimri Leisher
01/20/2021, 5:53 AMnanodeath
01/20/2021, 5:55 AMVampire
01/20/2021, 11:27 AM"oh \tmy god".split(" ")
res2: kotlin.collections.List<kotlin.String> = [oh, , <tab>my, , , god]
"oh \tmy god".split(" ").map { it.trim() }
res3: kotlin.collections.List<kotlin.String> = [oh, , my, , , god]
"oh \tmy god".split("""\s+""".toRegex())
res4: kotlin.collections.List<kotlin.String> = [oh, my, god]
Animesh Sahu
01/20/2021, 12:23 PM"oh \tmy god".splitToSequence(" ").map { it.trim() }.filter { it.isNotEmpty() }.toList()
res0: kotlin.collections.List<kotlin.String> = [oh, my, god]
blob thinking upside down
Edit: I checked regex version is faster (too much) -> 1ms vs 0.06ms ๐ฎAnimesh Sahu
01/20/2021, 12:26 PMVampire
01/20/2021, 1:08 PMZimri Leisher
01/23/2021, 10:20 PM