I have the string
a.b.c.d
I want to count the occurrences of '.' in an idiomatic way, preferably a one-liner.
(Previously I had expressed this constraint as "without a loop", in case you're wondering why everyone's trying to answer without using a loop).
My 'idiomatic one-liner' solution:
Have no idea why a solution that uses StringUtils is accepted.
While methods can hide it, there is no way to count without a loop (or recursion). You want to use a char[] for performance reasons though.
Using replaceAll (that is RE) does not sound like the best way to go.
You can use the
split()
function in just one line codeComplete sample:
Call:
ReplaceAll(".") would replace all characters.
PhiLho's solution uses ReplaceAll("[^.]",""), which does not need to be escaped, since [.] represents the character 'dot', not 'any character'.
Sooner or later, something has to loop. It's far simpler for you to write the (very simple) loop than to use something like
split
which is much more powerful than you need.By all means encapsulate the loop in a separate method, e.g.
Then you don't need have the loop in your main code - but the loop has to be there somewhere.