我有点迷茫
public static void main(String [] args){
String s = "a,b,c,d,";
System.out.println(s.split(",").length);
}
我期待看到 5 作为输出..但输出是 4? 为什么它会忽略最后一个“空”字段
如果我尝试解析具有(比如说)5 列的数据,我该如何处理这种情况。
cases:
a,b,c,d,e
a,,c,d,e //this case is fine as this still has 5 fields.. one of the field is missing.. but thats ok
a,b,c,d //simple length check with header catches this error
a,b,c,d,e,f //simple length check
a,b,c,d,e,// looks like there are 6 fields.. but unable to catch such error by length check
最佳答案
String#split()
方法忽略任何尾随的空字符串。所以,它们不是数组的一部分。如果您希望它们成为数组的一部分,请使用重载的 split(String, int)
方法,它将限制作为第二个参数。如果您为限制传递负值,则不会忽略尾随的空字符串。
System.out.println(s.split(",", -1).length);
而且,空字符串不是null
。
关于java - 如何在java中正确分割一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19071640/