java - 为什么 Kotlin 的 split ("") 函数会导致前导和尾随空字符串?

标签 java kotlin

我是一名 Java 开发人员,曾尝试过 Kotlin 并发现这两种语言之间存在违反直觉的情况。

考虑 Kotlin 中的给定代码:

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

在 Java 中也是如此:

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

为什么 Kotlin 在结果数组中产生前导和尾随空白字符串?还是 Java 总是删除这些空字符串,而我只是没有意识到这一点?

我知道每个 Kotlin String 上都有 toCharArray() 方法,但是,它仍然不是很直观(也许 Java 开发人员应该放弃从他们希望在新语言中重用 Java?)。

最佳答案

这是因为 Java split(String regex)方法显式删除它们:

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)提及:

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.

"" 是零宽度匹配。不确定为什么您认为 toCharArray() 在这里不直观,用空字符串拆分以遍历所有字符是一种迂回的做事方式。 split() 用于模式匹配并获取字符串组。

PS:我检查了 JDK 8、11 和 17,行为似乎暂时保持一致。

关于java - 为什么 Kotlin 的 split ("") 函数会导致前导和尾随空字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70941592/

相关文章:

java - OAuth2RestTemplate 身份验证问题获取 access_denied

java - 加密 encryptAES 和 decryptAES 在 play framework 2.6 中迁移

Java 无法在同一目录中的另一个 java 文件中找到类的符号

kotlin - 在 Kotlin 中检查 ArrayList 的类型

java - 在 Android 29 上启用禁用 WiFi

java - ByteArrayOutputStream 以 Java 声音录制时出现内存不足错误

android - setStartLineColor 和 setEndLineColor 不适用于时间轴 View

kotlin - IntelliJ Kotlin 变量建议

java - Android - Viewmodel 变大

java - 过滤负值