The difference between Kotlin's string and Java is split by Regex

If we have val txt: kotlin.String = "1;2;3;"and would like to break it into an array of numbers, we can try the following:

val numbers = string.split(";".toRegex())
//gives: [1, 2, 3, ]

The final empty is Stringincluded in the result CharSequence.split.

On the other hand, if we look at Java Strings, the result will be different:

val numbers2 = (string as java.lang.String).split(";")
//gives: [1, 2, 3]

This time using java.lang.String.split, the result will not contain an empty empty String. This behavior is really assumed in view of the corresponding JavaDoc:

This method works as if it were calling a split method with two arguments with a given expression and a limit argument of zero. Thus, trailing blank lines are not included in the resulting array .

Kotlin 0 limit , Kotlin , 0 -1, java.util.regex.Pattern::split :

nativePattern.split(input, if (limit == 0) -1 else limit).asList()

, , , , -, API Java, 0 .

+6
1

, java.lang.String.split limit = 0, . , , .

a:b:c:d: :.

, Java:

limit < 0[a, b, c, d, ]
limit = 0[a, b, c, d]
limit = 1[a:b:c:d:]
limit = 2[a, b:c:d:]
limit = 3[a, b, c:d:]
limit = 4[a, b, c, d:]
limit = 5[a, b, c, d, ] ( , limit < 0)
limit = 6[a, b, c, d, ]
...

, limit = 0 : :, , limit < 0 limit >= 5, ( limit 1..4).

, API Kotlin : , , , - ​​ .

IMO, , -, . - java.lang.String.split, , , . , , -, , .

+9

All Articles