我试图拆分一个字符串并保留空字符串。幸运的是,我找到了一个有前途的解决方案,它给了我预期的结果,如下REPL session 所述:
scala> val test = ";;".split(";",-1)
test: Array[String] = Array("", "", "")
我很好奇第二个参数实际上是做什么的,并深入到scala documentation中,但除了以下内容外,什么都没有找到:
同样在REPL解释器中,我仅获得以下信息:
scala> "asdf".split
标签
def split(String): Array[String]
def split(String, Int): Array[String]
问题
有人针对这些记录不良的参数有其他文献来源吗?
还是有人可以解释这个2dn参数对这个特定功能的作用?
最佳答案
这是与split
相同的java.lang.String
,碰巧它具有更好的documentation:
The limit parameter controls the number of times the pattern is applied and therefore affects the length of the resulting array. If the limit n is greater than zero then the pattern will be applied at most n - 1 times, the array's length will be no greater than n, and the array's last entry will contain all input beyond the last matched delimiter. If n is non-positive then the pattern will be applied as many times as possible and the array can have any length. If n is zero then the pattern will be applied as many times as possible, the array can have any length, and trailing empty strings will be discarded.
关于scala - StringOps.split(String,Int)中第二个参数的含义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24698666/