简体   繁体   English

String#split方法混淆

[英]String#split method confusion

I tried this code: 我试过这段代码:

String str =",,,,,";
String str2=",,,,, ";
System.out.println(str.split(",").length);
System.out.println(str2.split(",").length);

And the output is: 输出是:

0
6

The only difference is str value is ,,,,, ( without space ) and str2 value is ,,,,, ( with space ) 唯一的区别是str值是,,,,,没有 空格 )和str2值是,,,,, 空格

Anybody can explain this? 有人可以解释一下吗?

Because in String#split() method, trailing empty String will not included in the array result. 因为在String#split()方法中,尾随空的String不会包含在数组结果中。

String str =",,,,,";
String str2=",,,,, ";

As str.split(",") will supposed to give you [, , , , ,] , It return [] instead, because you have a trailing empty String there. 因为str.split(",")会给你[, , , , ,] str.split(",") [, , , , ,] ,它会返回[] ,因为你在那里有一个尾随的空字符串

Different from str2.split(",") it will give you str2.split(",")不同str2.split(",")它会给你

[, , , , , ]
          ^ //note the whitespace element 

You may try 你可以试试

System.out.println(",,,,, ,,,,".split(",").length);

This will still give you the output: 6 , which is [, , , , , ] because after the whitespace , all you have is trailing empty string (therefore not included in the array result) 这仍然会给你输出: 6 ,这是[, , , , , ] ,,,,, [, , , , , ]因为在空格之后 ,你所有的都是尾随空字符串(因此不包含在数组结果中)


Note: You can keep the trailing empty strings by specifying the limit: 注意:您可以通过指定限制来保留尾随空字符串:

System.out.println(str.split(",", -1).length);
                                   ^ limit

Output : 6 产量: 6

Check the String#split Documentation for more details 有关详细信息,请查看String#split文档

This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array. taken from the String documentation. 取自String文档。

Had your second string been ",,, ,," then the length would have been 4. 如果你的第二个字符串是",,, ,,"那么长度就是4。

Hope that explains it clearly. 希望能清楚地解释清楚。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM