Java split() 方法最后去除空字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/545957/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 16:04:00  来源:igfitidea点击:

Java split() method strips empty strings at the end?

javasplit

提问by raja

Check out the below program.

看看下面的程序。

try {
    for (String data : Files.readAllLines(Paths.get("D:/sample.txt"))){
        String[] de = data.split(";");
        System.out.println("Length = " + de.length);
    }
} catch (IOException e) {
    e.printStackTrace();
}

Sample.txt:

示例.txt:

1;2;3;4
A;B;;
a;b;c;

Output:

输出:

Length = 4
Length = 2
Length = 3

Why second and third output is giving 2 and 3 instead of 4. In sample.txtfile, condition for 2nd and 3rd line is should give newline(\nor enter) immediately after giving delimiter for the third field. Can anyone help me how to get length as 4 for 2nd and 3rd line without changing the condition of the sample.txtfile and how to print the values of de[2](throws ArrayIndexOutOfBoundsException)?

为什么第二个和第三个输出是 2 和 3 而不是 4。在sample.txt文件中,第 2 行和第 3 行的条件是应该\n在为第三个字段提供分隔符后立即给出换行符(或输入)。任何人都可以帮助我如何在不更改sample.txt文件条件的情况下将第 2 行和第 3 行的长度设为 4以及如何打印de[2](throws ArrayIndexOutOfBoundsException)的值?

回答by Johannes Weiss

have a look at the docs, here the important quote:

看看文档,这里是重要的引用:

[...] the array can have any length, and trailing empty strings will be discarded.

If you don't like that, have a look at Fabian's comment. When calling String.split(String), it calls String.split(String, 0)and that discards trailing empty strings (as the docs say it), when calling String.split(String, n)with n < 0it won't discard anything.

如果您不喜欢那样,请查看 Fabian 的评论。当调用 时String.split(String),它会调用String.split(String, 0)并丢弃尾随的空字符串(正如文档所说),当String.split(String, n)n < 0它调用时不会丢弃任何东西。

回答by Fabian Steeg

You can specify to apply the pattern as often as possible with:

您可以指定尽可能频繁地应用该模式:

String[] de = data.split(";", -1);

See the Javadocfor the split method taking two arguments for details.

有关详细信息,请参阅带有两个参数的 split 方法的 Javadoc