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).
A shorter example is
I had an idea similar to Mladen, but the opposite...
I don't like the idea of allocating a new string for this purpose. And as the string already has a char array in the back where it stores it's value, String.charAt() is practically free.
does the trick, without additional allocations that need collection, in 1 line or less, with only J2SE.
Summarize other answer and what I know all ways to do this using a one-liner:
1) Using Apache Commons
2) Using Spring Framework's
3) Using replace
4) Using replaceAll (case 1)
5) Using replaceAll (case 2)
6) Using split
7) Using Java8 (case 1)
8) Using Java8 (case 2), may be better for unicode than case 1
9) Using StringTokenizer
From comment: Be carefull for the StringTokenizer, for a.b.c.d it will work but for a...b.c....d or ...a.b.c.d or a....b......c.....d... or etc. it will not work. It just will count for . between characters just once
More info in github
Perfomance test (using JMH, mode = AverageTime, score
0.010
better then0.351
):