Java String split 删除空值 [英] Java String split removed empty values

查看:36
本文介绍了Java String split 删除空值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用分隔符拆分值.但我发现了令人惊讶的结果

I am trying to split the Value using a separator. But I am finding the surprising results

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 个值.

I am expecting to get 8 values. [5,6,7,EMPTY,8,9,EMPTY,EMPTY] But I am getting only 6 values.

任何想法以及如何解决.不管 EMPTY 值出现在任何地方,它都应该在数组中.

Any idea and how to fix. No matter EMPTY value comes at anyplace, it should be in array.

推荐答案

split(delimiter) 默认从结果数组中删除尾随空字符串.要关闭此机制,我们需要使用 split(delimiter, limit) 的重载版本,将 limit 设置为负值,如

split(delimiter) by default removes trailing empty strings from result array. To turn this mechanism off we need to use overloaded version of split(delimiter, limit) with limit set to negative value like

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

更多细节:
split(regex) 内部返回 split(regex, 0)文档(重点是我的)

Little more details:
split(regex) internally returns result of split(regex, 0) and in documentation of this method you can find (emphasis mine)

limit 参数控制应用模式的次数,因此会影响结果数组的长度.

The limit parameter controls the number of times the pattern is applied and therefore affects the length of the resulting array.

如果限制n大于零,则该模式最多应用n - 1次,数组的长度不大于n,并且数组的最后一个条目将包含最后一个匹配的分隔符之外的所有输入.

If the limit n is greater than zero then the pattern will be applied at most n - 1 times, the array's length will be no greater than n, and the array's last entry will contain all input beyond the last matched delimiter.

如果 n非正,那么该模式将被尽可能多地应用并且数组可以有任何长度.

If n is non-positive then the pattern will be applied as many times as possible and the array can have any length.

如果 n0 则模式将被应用尽可能多的次数,数组可以有任何长度,并且 尾随空字符串将被丢弃.

If n is zero then the pattern will be applied as many times as possible, the array can have any length, and trailing empty strings will be discarded.

例外:

值得一提的是,删除尾随空字符串才有意义只有当这种空字符串是由拆分机制创建的时候才有意义.所以对于 "".split(anything) 因为我们不能将 "" 拆分得更远,我们将得到结果 [""] 数组.
这是因为这里没有发生拆分,所以 "" 尽管是空的,尾随代表 原始 字符串,而不是 创建的空字符串 通过拆分过程.

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.

这篇关于Java String split 删除空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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