2

Given following string:

String s ="12/15|22:58:25|B|99.502||||A|100.501|||||";

I am calling

int len = s.split("\\|").length;

Anyway length is 9, not 13 as it should be.

Nevertheless, if I modify said string in this way:

String s ="12/15|22:58:25|B|99.502||||A|100.501|||lol||";

Length is 13! How come?It just seems that java makes some kind of optimization, which is not required as those parts of string could be populated in some other context...

Pshemo
  • 122,468
  • 25
  • 185
  • 269
Phate
  • 6,066
  • 15
  • 73
  • 138

1 Answers1

8

By default split removes trailing empty strings from result array. To turn off this mechanism use split(regex, limit) with negative limit like

split("\\|", -1)

Little more details:
split(regex) internally returns result of split(regex, 0) and in documentation of this method you can find (emphasis mine)

The limit parameter controls the number of times the pattern is applied and therefore affects the length of the resulting array.

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.

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.

Community
  • 1
  • 1
Pshemo
  • 122,468
  • 25
  • 185
  • 269