java - Split 方法忽略末尾的逗号

标签 java string

当我用多个逗号分割一个字符串时,它们在数组中被忽略。这是对的吗 ?

    String a = "a,b,c,,f,,";
    String[] sdf = a.split(",");
    for (int i = 0; i < sdf.length; i++) {
        System.out.println(sdf[i]);
    }

或者我错过了什么。

我得到的输出是

[a,b,c, ,f]   

我想考虑这些空白值,期待这样的事情

[a,b,c, ,f, ,] 

最佳答案

您需要使用:

public String[] split(String regex,
                  int limit)

并说:

String[] sdf = a.split(",", -1);

对于您的输入,它会产生:

[a, b, c, , f, , ]

引自documentation :

If n is non-positive then the pattern will be applied as many times as possible and the array can have any length.

关于java - Split 方法忽略末尾的逗号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20068416/

相关文章:

c++ - 在 C++ 中以这种方式创建字符串数组是否正确?

c# - 删除字母或标记出来只留下数字和撇号

c# - 如何在数组中添加值

java - bazel run *_deploy.jar 失败并显示 "cannot execute binary file"

java - 如何在 Java 中对空字符串应用 toUpperCase()?

java - 我可以为动态数组列表父类(super class)类型对象创建子类对象吗?

java - java中复杂的字符串提取

java - 内存不足的最快方法

arrays - Bash:循环遍历字符串数组后无法读出带空格的字符串

c - 搜索 char** 类型的字符串