Home > front end >  Kotlin split("") contains leading and trailing empty string
Kotlin split("") contains leading and trailing empty string

Time:02-01

I'm Java developer who tried Kotlin and I found some counterintuitive case between these to languages.

Consider given code in Kotlin:

"???".split("")  # gives ["", "?", "?", "?", ""]

and the same one in Java

"???".split("")  # gives ["?", "?", "?"]

Why Kotlin produces leading and trailing empty space string in resulting array ? Or maybe Java always removes these empty strings that I wasn't aware of ?

P.S. Yes, I know that there is toCharArray() method on each Kotlin's String, but still it's not very intuitive (maybe Java developers should give up old habits from Java which they were hope to reuse in new language ?)

Let's discuss :)

CodePudding user response:

This is because the Java split(String regex) method explicitly removes them:

This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.

split(String regex, int limit) mentions:

When there is a positive-width match at the beginning of this string then an empty leading substring is included at the beginning of the resulting array. A zero-width match at the beginning however never produces such empty leading substring.

"" is a zero-width match. Not sure why you consider toCharArray() to not be intuitive here, splitting by an empty string to iterate over all characters is a roundabout way of doing things. split() is intended to pattern match and get groups of Strings.

PS: I checked JDK 8, 11 and 17, behavior seems to be consistent for a while now.

CodePudding user response:

You need to filter out the first and last element:

"???".split("").drop(1).dropLast(1)

Check out this example:

"".split("")   // [, ]

Splits this char sequence to a list of strings around occurrences of the specified delimiters.

See https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.text/split.html

  •  Tags:  
  • Related