我正在try 使用分隔符拆分值.
String data = "5|6|7||8|9||";
String[] split = data.split("\\|");
System.out.println(split.length);
我希望得到8个值.[5,6,7,EMPTY,8,9,EMPTY,EMPTY]个 但是我只得到了6个值.
任何 idea 以及如何修复.不管空值在任何地方出现,它都应该在数组中.
我正在try 使用分隔符拆分值.
String data = "5|6|7||8|9||";
String[] split = data.split("\\|");
System.out.println(split.length);
我希望得到8个值.[5,6,7,EMPTY,8,9,EMPTY,EMPTY]个 但是我只得到了6个值.
任何 idea 以及如何修复.不管空值在任何地方出现,它都应该在数组中.
默认情况下,split(delimiter)
将从结果数组中删除尾随的空字符串.要关闭这个机制,我们需要使用split(delimiter, limit)
的重载版本,将limit
设置为负值,如
String[] split = data.split("\\|", -1);
Little more details:
split(regex)
internally returns result of split(regex, 0)
and in documentation of this method you can find (emphasis mine)
limit
参数控制应用数组的次数,因此会影响生成数组的长度.如果限制
n
是greater than zero,则模式最多应用n-1次,数组长度将不大于n,数组的最后一个条目将包含最后一个匹配分隔符之外的所有输入.如果
n
是non-positive,则将尽可能多次应用图案,并且数组可以具有任意长度.如果
n
是zero,则图案将被应用尽可能多的次数,数组可以具有任意长度,并且为trailing empty strings will be discarded.
Exception:
It is worth mentioning that removing trailing empty string makes sense only if such empty strings were created by the split mechanism. So for "".split(anything)
since we can't split ""
farther we will get as result [""]
array.
It happens because split didn't happen here, so ""
despite being empty and trailing represents original string, not empty string which was created by splitting process.