2

After you split an empty string, you get an array of 1 element After you split a string that have only separators/delimiters(for example, only special characters which the split(\W) will remove), you get an array of 0 elements?

They both lead to empty tokens so surely they have the same length arrays? But why not?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Kerage Chan
  • 116
  • 1
  • 9

1 Answers1

3

Because, split have two case:

  1. If no match was found, return new String[] { this }, for example:

    "1111".split(",") // {"1111"}
    " ".split(",") // {" "}
    "".split(",") // {""}
    
  2. It match was found, return new String[resultSegmentCount], when resultSegmentCount = 0, for example:

     " , ".split(",") // {" ", " "}
     " ,".split(",") // {" "}
     ", ".split(",") // {" "}
     ",".split(",") // {}
    
Slava Vedenin
  • 58,326
  • 13
  • 40
  • 59
  • You can see the current source code of the `String.split(String, int)` method [at grepcode](http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8u40-b25/java/lang/String.java#String.split%28java.lang.String%2Cint%29). Note that `String.split(String)` simply calls `String.split(String, int)` with an integer argument of zero. – Bobulous Sep 03 '17 at 19:42