Confusing output from String.split

前端 未结 8 1027
情深已故
情深已故 2020-12-08 06:33

I do not understand the output of this code:

public class StringDemo{              
    public static void main(String args[]) {
        String blank = \"\";         


        
8条回答
  •  感动是毒
    2020-12-08 07:00

    From the Java 1.7 Documentation

    Splits the string around matches of the given regular expression.

    split() 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.

    In the Case 1 blank.split(",") does not match any part of the input then the resulting array has just one element, namely this String.

    It will return entire String. So, the length will be 1.

    In the Case 2 comma.split(",") will return empty.

    split() expecting a regex as argument, return result array to matching with that regex.

    So, the length is 0

    For Example(Documentation)

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

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

    Parameters: regex - the delimiting regular expression

    Returns: the array of strings computed by splitting this string around matches of the given regular expression

    Throws: PatternSyntaxException - if the regular expression's syntax is invalid

提交回复
热议问题