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

前端 未结 3 1709
爱一瞬间的悲伤
爱一瞬间的悲伤 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条回答
  •  生来不讨喜
    2020-11-22 04:07

    This has been specified in the documentation of split(String regex, limit).

    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.

    In "abc".split("") you got a zero-width match at the beginning so the leading empty substring is not included in the resulting array.

    However in your second snippet when you split on "a" you got a positive width match (1 in this case), so the empty leading substring is included as expected.

    (Removed irrelevant source code)

提交回复
热议问题