0

how can I sucessfully count the numbers of values in a String that are seperated through a semicolon(including empty values)?

I have for example this String:

;;C;D;E;F;G

The correct number of values would be '7', but when I use .split it returns the wrong number, because of the empty values.

How can I fix this?

Pshemo
  • 122,468
  • 25
  • 185
  • 269

2 Answers2

3

Example from your question works fine since

System.out.println(";;C;D;E;F;G".split(";").length);

prints 7.

But problem could appear when empty elements are at end of your string like

System.out.println(";;C;D;E;F;G;;".split(";").length);

which also would return 7. Why is that? Because split(regex) uses split(regex,limit) version with limit set to 0. This limit represents behaviour of split in which trailing empty elements will be removed.

If you don't want to remove trailing empty elements use negative limit like

System.out.println(";;C;D;E;F;G;;".split(";", -1).length);
//                                            ^^-negative limit

which will now print 9.

Pshemo
  • 122,468
  • 25
  • 185
  • 269
2

String#split() may return return a wrong number because of the empty values only if the separators are at the tail of text, e.g. ";;C;D;E;F;G;;". To avoid that use text.split(regex, -1)

Alex Salauyou
  • 14,185
  • 5
  • 45
  • 67
Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275