0 votes
1 view
in Java by (2.3k points)

I have the string


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).

1 Answer

0 votes
by (21.4k points)

Here's one 'idiomatic one-liner' to count the occurrences of a char in a string:

int count = StringUtils.countMatches("a.b.c.d", ".");

Check out this common Lang doc.

or you can also try this Spring Framework's oneliner:

int occurrence= StringUtils.countOccurrencesOf("a.b.c.d", ".");