我有一个 csv 格式的数据文件。
我正在尝试使用基本拆分命令 line.split(',')
拆分每一行
但是当我得到这样的字符串时 "2,,"
,
而不是像这样返回一个数组 Array(2,"","")
我刚收到一个 Array: Array(2)
.
我绝对错过了一些基本的东西,有人可以帮助指出在此处拆分逗号分隔字符串的正确方法吗?
最佳答案
这是从Java继承的。您可以使用 split(String regex, int limit)
实现您想要的行为。重载:
"2,,".split(",", -1) // = Array(2, "", "")
请注意
String
而不是 Char
.正如 Java Docs 所解释的,
limit
参数使用如下: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.
Source
使用
split(separator: Char)
将使用 limit
调用上面的重载零。
关于string - 在 Scala : Missing Trailing Empty Strings? 中拆分逗号分隔的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24273896/