String test="I am preparing for OCPJP";
String[] tokens=test.split("\\S");
System.out.println("length:"+tokens.length);
for(String s:tokens) {
System.out.print("["+s+"]");
}
System.out.println();
输出:
length:16
[][ ][][ ][][][][][][][][][ ][][][ ]
现在我将 split(regex) 更改为 split(regex,limit)
输出:
length:21
[][ ][][ ][][][][][][][][][ ][][][ ][][][][][]
你能告诉我为什么这个结果不同吗?非常感谢!
Javadocs for the 2-arg overload of split
状态:
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.
Javadocs for the 1-arg overload of 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.
而 1-arg,无限制重载等同于 0
的限制。对于非零限制,尾随的空字符串不再被丢弃。不再丢弃的那 5 个尾随空字符串对应于在“OCPJP”中找到的非空格。