-3

I have a String, which contains a lot of commas.

I want to count all the commas in the String but I don't know how.

I'm using (split(",")-1)

But the problem is that if I input a String like this: One,Two,Three,Four,,,

Then it returns only 3 while I want it to be 6.

I think it is because split(",") returns a String[] that does not include null or empty values.

Is there any way to solve this problem?

James Dunn
  • 8,064
  • 13
  • 53
  • 87
  • 2
    Does this answer your question? [How do I count the number of occurrences of a char in a String?](https://stackoverflow.com/questions/275944/how-do-i-count-the-number-of-occurrences-of-a-char-in-a-string) – namgold Dec 29 '20 at 07:20

1 Answers1

2

One straightforward way would be to just compare the length of the input against the input with all commas removed:

String input = "One,Two,Three,Four,,,";
int numCommas = input.length() - input.replace(",", "").length();
System.out.println(numCommas);  // prints 6
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360