[英]String#split method confusion
我試過這段代碼:
String str =",,,,,";
String str2=",,,,, ";
System.out.println(str.split(",").length);
System.out.println(str2.split(",").length);
輸出是:
0
6
唯一的區別是str
值是,,,,,
( 沒有 空格 )和str2
值是,,,,,
( 帶 空格 )
有人可以解釋一下嗎?
因為在String#split()
方法中,尾隨空的String不會包含在數組結果中。
String str =",,,,,";
String str2=",,,,, ";
因為str.split(",")
會給你[, , , , ,]
str.split(",")
[, , , , ,]
,它會返回[]
,因為你在那里有一個尾隨的空字符串 。
與str2.split(",")
不同str2.split(",")
它會給你
[, , , , , ]
^ //note the whitespace element
你可以試試
System.out.println(",,,,, ,,,,".split(",").length);
這仍然會給你輸出: 6
,這是[, , , , , ]
,,,,, [, , , , , ]
因為在空格之后 ,你所有的都是尾隨空字符串(因此不包含在數組結果中)
注意:您可以通過指定限制來保留尾隨空字符串:
System.out.println(str.split(",", -1).length);
^ limit
產量: 6
有關詳細信息,請查看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.
取自String文檔。
如果你的第二個字符串是",,, ,,"
那么長度就是4。
希望能清楚地解釋清楚。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.