idiomatic way to do stuff like `val words = input....
# announcements
z
idiomatic way to do stuff like
val words = input.split(" ").map { it.trim() }
?
e
.split() already excludes the splitter from the results
z
oh, really? great. for some reason i was under the impression that it didn't
a
You can
input.split(" ") { it.trim() }
Oh wait, its for
joinToString
actually...
n
not that you needed to in this case, per @ephemient, but I'd use
splitToSequence
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.
K 1
a
split
also accepts a regex so you could do
Copy code
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.
z
@nanodeath super helpful thanks, and @Ahmed Mourad you too ๐Ÿ™‚
๐Ÿ‘ 3
n
@Ahmed Mourad but now you're compiling regexes ๐Ÿ™ƒ
๐Ÿ˜ž 1
v
Well, it heavily depends on what you want to achieve
Copy code
"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]
๐Ÿ‘ 2
a
Hm,
Copy code
"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 ๐Ÿ˜ฎ
Go with regex!
v
Of course it is faster, Regex is meant for text processing, having a 4 step sequence processing needs time. ๐Ÿ˜„ You can probably go even faster if you pre-compile the regex, at least if the code is called multiple times.
๐Ÿ’ฏ 2
z
good to know ๐Ÿ™‚