Java split() 方法最后去除空字符串? [英] Java split() method strips empty strings at the end?

查看:179
本文介绍了Java split() 方法最后去除空字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

查看以下程序.

尝试{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();}

示例.txt:

<前>1;2;3;4甲;乙;;a;b;c;

输出:

<前>长度 = 4长度 = 2长度 = 3

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

解决方案

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

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

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

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:

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.txt file, condition for 2nd and 3rd line is should give newline( or 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.txt file and how to print the values of de[2] (throws ArrayIndexOutOfBoundsException)?

解决方案

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

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

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

这篇关于Java split() 方法最后去除空字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆