Why in Java 8 split sometimes removes empty strings at start of result array?

前端 未结 3 1635
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-22 03:17

Before Java 8 when we split on empty string like

String[] tokens = \"abc\".split(\"\");

split mechanism would split in pl

3条回答
  •  梦毁少年i
    2020-11-22 03:41

    There was a slight change in the docs for split() from Java 7 to Java 8. Specifically, the following statement was added:

    When there is a positive-width match at the beginning of this string then an empty leading substring is included at the beginning of the resulting array. A zero-width match at the beginning however never produces such empty leading substring.

    (emphasis mine)

    The empty string split generates a zero-width match at the beginning, so an empty string is not included at the start of the resulting array in accordance with what is specified above. By contrast, your second example which splits on "a" generates a positive-width match at the start of the string, so an empty string is in fact included at the start of the resulting array.

提交回复
热议问题