split()在delimiters =空字符串之间没有任何内容

时间:2012-07-31 22:54:31

标签: java

想象一下你有:

String string = "A;B;;D";
String[] split = string.split(";");

我希望结果是:

split[0] = "A";
split[1] = "B";
split[2] = "";
split[3] = "D";

但结果是:

split[0] = "A";
split[1] = "B";
split[2] = "D";

对此有简单的正确方法吗?

3 个答案:

答案 0 :(得分:10)

使用重载方法split(String regex, int limit)

String string = "A;B;;D";
String[] split = string.split(";", -1);

来自documentation

The string "boo:and:foo", for example, yields the following results with these parameters:

    Regex   Limit   Result
    :   2   { "boo", "and:foo" }
    :   5   { "boo", "and", "foo" }
    :   -2  { "boo", "and", "foo" }
    o   5   { "b", "", ":and:f", "", "" }
    o   -2  { "b", "", ":and:f", "", "" }
    o   0   { "b", "", ":and:f" }

答案 1 :(得分:4)

我个人使用GuavaSplitter课程:

Iterable<String> bits = Splitter.on(';').split(string);

如果你想要它省略空字符串,你只需使用:

Iterable<String> bits = Splitter.on(';').omitEmptyStrings().split(string);

没有令人讨厌的隐含正则表达式,并且所有内容都符合它所说的。好多了:))

在现实生活中,我可能会将分割器创建一次作为静态最终变量。 (如果您认为为单个类导入Guava是过度的,请查看库的其余部分。它非常有用 - 如果没有它,我不希望用Java开发。)

答案 2 :(得分:0)

您只需要在split函数中包含第二个参数,这是您在分割之间接受的最小字符数,在您的情况下为0。

所以电话应该是这样的:

String[] split = string.split(";", 0);

使用限制0来丢弃尾随的空字符串,或使用负值来保留它们。 在此处查找文档:Javadoc