12

http://www.tutorialspoint.com/java/java_string_split.htm

Here is the syntax of this method: public String[] split(String regex, int limit) or public String[] split(String regex)

In the above link, I can understand the Str.split("-", 2) and Str.split("-", 3) examples.

However, I don't quite get the Str.split("-", 0), what's the role of zero of the limit? In some examples, I have also encountered negative limits, what is this?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • 4
    http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split%28java.lang.String,%20int%29 – Syam S Jul 11 '14 at 15:24
  • Copy-pasted for your convenience: "f n is non-positive then the pattern will be applied as many times as possible and the array can have any length.If n is zero then the pattern will be applied as many times as possible, the array can have any length, and trailing empty strings will be discarded." – laune Jul 11 '14 at 15:27
  • @laune You missed the prior sentence! Not surprising, since *non-positive* isn't **obviously** negative. *If n is non-positive then the pattern will be applied as many times as possible and the array can have any length. If n is zero then the pattern will be applied as many times as possible, the array can have any length, and trailing empty strings will be discarded.* So, a zero discard empty records and a negative preserves them! – Elliott Frisch Jul 11 '14 at 15:28
  • @ElliottFrisch Yes, my scanner was definitely set too narrow ;-o Thanks. – laune Jul 11 '14 at 15:31

3 Answers3

21

The limit parameter controls the number of times the pattern is applied and therefore affects the length of the resulting array. We have 3 possible values for this limit:

  1. If the limit n is greater than zero then the pattern will be applied at most n - 1 times, the array's length will be no greater than n, and the array's last entry will contain all input beyond the last matched delimiter.

  2. If n is non-positive then the pattern will be applied as many times as possible and the array can have any length.

  3. If n is zero then the pattern will be applied as many times as possible, the array can have any length, and trailing empty strings will be discarded.

You can read more here.

GingerHead
  • 8,130
  • 15
  • 59
  • 93
9

Str.split("-",0) is the same as Str.split("-")

soorapadman
  • 4,451
  • 7
  • 35
  • 47
dari
  • 2,255
  • 14
  • 21
2

Str.split("-", 0) is equivalent to Str.split("-"). I.e, there's no limit.

Eran
  • 387,369
  • 54
  • 702
  • 768