[英]Java String split result
I don't understand why this is getting an output of 3: 我不明白为什么这会得到3的输出:
String[] split = "name:john;;sex:m;;".split(";");
System.out.println(Arrays.toString(split) + " size " + split.length);
I have read Oracle documentation and I still wihout getting why is 3. 我已经阅读了Oracle文档,但仍然不知道为什么是3。
Why the output is: 为什么输出为:
[name:john, , sex:m] size 3
Where is taking the ' ' (the second on the list), and also why the ";;" 在哪里使用“”(列表中的第二个),以及为什么“ ;;” at the end is not in the output. 最后没有出现在输出中。
split(";")
will get strings from before, between, and after each single semicolon. split(";")
将在每个分号之前,之间和之后获取字符串。 So your split
array would theoretically be {"name:john","","sex:m","",""}
at some point in the operation. 因此,在操作过程中的某个时刻,您的split
数组理论上将为{"name:john","","sex:m","",""}
。 However, split()
removes trailing empty strings, so you actually get {"name:john","","sex:m"}
. 但是, split()
删除了结尾的空字符串,因此您实际上得到了{"name:john","","sex:m"}
。
As to why you don't have a terminal semicolons being printed, is because you split over each individual semicolon without a limit. 至于为什么没有打印终端分号的原因,是因为您可以无限制地分割每个单独的分号。 The limit
is length of the resulting array. limit
是结果数组的长度。
You can often fix internal empty strings by using the proper regex
for multiple characters. 您通常可以通过对多个字符使用正确的regex
来修复内部空字符串。 You may want to check split(";++")
. 您可能要检查split(";++")
。 If you want the terminal semicolons you need to set a limit split(";++",2)
. 如果要使用终端分号,则需要设置一个限制split(";++",2)
。
It looks like Arrays.toString
is representing your split
array with space characters, instead of what it would actually be in the array of Strings returned by String.split
, which is the empty string ""
. 看起来Arrays.toString
用空格字符表示split
数组,而不是用String.split
返回的String数组中的实际值,它是空字符串""
。 The final two semicolons on the end are not in the output because String.split
only inserts the empty strings into its array where the delimiter you specify occurs within the string, not after it ends. 最后的两个分号不在输出中,因为String.split
仅将空字符串插入其数组中您指定的分隔符出现在其数组中的位置,而不是在字符串结束之后。
The ''
is from the two semicolons that you put in between name:john
and sex:m
. ''
来自您在name:john
和sex:m
之间插入的两个分号。 The fact that they are not at the end is because java ignores empty strings at the end of a list. 它们不在末尾的事实是因为java会忽略列表末尾的空字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.