public class SplitDemo { public static void main(String[] args) { String a = "abcooob"; String[] as = a.split("o"); System.out.println(as.length); } }
運行結果是
4
abc b
因爲分割成{“abc”,"","","b"}的值,這個正常理解。
public class SplitDemo { public static void main(String[] args) { String a = "abcooo"; String[] as = a.split("o"); System.out.println(as.length); for (String string : as) { System.out.print(string+"\t"); } } }
這個運行結果是:
1
abc
---------------------------------------------------------
爲什麼呢?
看api
split
public String[] split(String regex)
根據給定正則表達式的匹配拆分此字符串。
該方法的作用就像是使用給定的表達式和限制參數 0 來調用兩參數
split
方法。因此,所得數組中不包括結尾空字符串。例如,字符串 "boo:and:foo" 使用這些表達式可生成以下結果:
Regex 結果 : { "boo", "and", "foo" } o { "b", "", ":and:f" } 參數:
regex
- 定界正則表達式返回:
字符串數組,它是根據給定正則表達式的匹配拆分此字符串確定的
拋出:
PatternSyntaxException
- 如果正則表達式的語法無效
----------------------------------------------------------------------------------
結論:split分割所得數組中不包括結尾空字符串。
----------------------------------------------------------------------------------