Behaviour of String.split in java 1.6?

只愿长相守 提交于 2019-12-20 03:23:32

问题


My code is:

String s = "1;;;; 23;;";
System.out.println(s.split(";").length);

and gives as output 5. The source code of split is:

public String[] split(String regex) {
        return split(regex, 0);
    }

and the documentation says:

This method works as if by invoking the two-argument split(java.lang.String,int) method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.

The string "boo:and:foo", for example, yields the following results with these expressions:

Regex Result
: { "boo", "and", "foo" }
o { "b", "", ":and:f" }

If I print the strings I have:

1



 23

Shouldn't I get from this 1;;;; 23;; something like {"1", "", "", "", " 23", ""} ?


回答1:


No, five is correct, as your quoted docs state:

Trailing empty strings are therefore not included in the resulting array.

Which is why the empty strings at the end of the array are omitted. If you want the empty strings, do as Evgeniy Dorofeev's answer says and specify a limit of -1.




回答2:


Since limit = 0 trailing empty strings are not included. Try

System.out.println(s.split(";", -1).length);

and you will get 7




回答3:


It will split the string when ever ';' present and put into array.



来源:https://stackoverflow.com/questions/14056813/behaviour-of-string-split-in-java-1-6

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!