Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split String to Pair

Tags:

kotlin

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", "")

like image 630
VsSekorin Avatar asked Oct 15 '25 16:10

VsSekorin


1 Answers

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.).

like image 180
Salem Avatar answered Oct 17 '25 04:10

Salem



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!