string - 在 Scala : Missing Trailing Empty Strings? 中拆分逗号分隔的字符串

标签 string scala split

我有一个 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/

相关文章:

python - 如何在字符串文字中放置实际的反斜杠(不将其用于转义序列)?

mysql - 选择并计算列

scala - 在 Play Framework 中使用 orm 时如何添加缓存机制

scala - 是否有可能以及如何让 Scala par 消耗线程池中的线程?

java - 如何检查字符是否为元音?

python - 连接不同列表中的两个字符串

scala - 如何在 Scala 中覆盖 Java varargs 方法?

Python - 拆分包含 '\x' 的字符串

java - 拥有一个字符串,替换然后执行拆分或拥有一组字符串并创建一个新的字符串来更改它会更有效吗?

python - 使用前缀分割大型 .gz 文件