Java split()方法最后会删除空字符串? [英] Java split() method strips empty strings at the end?
问题描述
查看以下程序。
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:
Sample.txt:
1;2;3;4
A;B;;
a;b;c;
输出:
Length = 4
Length = 2
Length = 3
为什么第二和第三输出给出2和3而不是4。 sample.txt
文件,第2行和第3行的条件应该立即给出换行符( \ n
或输入)给第三个字段的分隔符。任何人都可以帮助我如何在不改变 sample.txt
文件的条件的情况下获得第2行和第3行的长度为4,以及如何打印 de [2]
(抛出 ArrayIndexOutOfBoundsException
)?
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(\n
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);
有关详细信息,请参阅Javadoc 获取有两个参数的split方法。
See the Javadoc for the split method taking two arguments for details.
这篇关于Java split()方法最后会删除空字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!