我是一名 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/