Skip to content
Advertisement

How do I count the number of occurrences of a char in a String?

I have the string

JavaScript

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

Advertisement

Answer

My ‘idiomatic one-liner’ for this is:

JavaScript

Why write it yourself when it’s already in commons lang?

Spring Framework’s oneliner for this is:

JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement