Confusing output from String.split

前端 未结 8 1026
情深已故
情深已故 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:11

    We can take a look into the source code of java.util.regex.Pattern which is behind String.split. Way down the rabbit hole the method

    public String[] split(CharSequence input, int limit)
    

    is invoked.

    Input ""

    For input "" this method is called as

    String[] parts = split("", 0);
    

    The intersting part of this method is:

      int index = 0;
      boolean matchLimited = limit > 0;
      ArrayList matchList = new ArrayList<>();
      Matcher m = matcher(input);
    
      while(m.find()) {
        // Tichodroma: this will not happen for our input
      }
    
      // If no match was found, return this
      if (index == 0)
        return new String[] {input.toString()};
    

    And that is what happens: new String[] {input.toString()} is returned.

    Input ","

    For input ","the intersting part is

        // Construct result
        int resultSize = matchList.size();
        if (limit == 0)
            while (resultSize > 0 && matchList.get(resultSize-1).equals(""))
                resultSize--;
        String[] result = new String[resultSize];
        return matchList.subList(0, resultSize).toArray(result);
    

    Here resultSize == 0 and limit == 0 so new String[0] is returned.

提交回复
热议问题