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).
Okay, inspired by Yonatan's solution, here's one which is purely recursive - the only library methods used are
length()
andcharAt()
, neither of which do any looping:Whether recursion counts as looping depends on which exact definition you use, but it's probably as close as you'll get.
I don't know whether most JVMs do tail-recursion these days... if not you'll get the eponymous stack overflow for suitably long strings, of course.
Here is a slightly different style recursion solution:
How about this. It doesn't use regexp underneath so should be faster than some of the other solutions and won't use a loop.
With java-8 you could also use streams to achieve this. Obviously there is an iteration behind the scenes, but you don't have to write it explicitly!
Also possible to use reduce in Java 8 to solve this problem:
Output:
In case you're using Spring framework, you might also use "StringUtils" class. The method would be "countOccurrencesOf".