I try split String on two: text.split("\\s+".toRegex(), 2). But I have no guarantees that there will be exactly two. Example: "abc".split("\\s+".toRegex(), 2).size == 1.
Is it possible to split String into two parts? Or get Pair<String, String>?
Update. Expected result:
"123 456 789 0" -> ("123", "456 789 0") or listOf("123", "456 789 0")
"123" -> ("123", "") or listOf("123", "")
Why not:
Pair(text.substringBefore(' ').trim(), text.substringAfter(' ').trim())
This depends, of course, on whether you want to split on all spaces and ignore any more than 2 strings:
text.split(Regex("\\s+")).let {
Pair(it[0], it.getOrNull(1) ?: "")
}
or if you want to split on the last space (use substringBeforeLast, etc.).
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