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).
here is a solution without a loop:
well, there is a loop, but it is invisible :-)
-- Yonatan
Somewhere in the code, something has to loop. The only way around this is a complete unrolling of the loop:
...etc, but then you're the one doing the loop, manually, in the source editor - instead of the computer that will run it. See the pseudocode:
Not sure about the efficiency of this, but it's the shortest code I could write without bringing in 3rd party libs:
Inspired by Jon Skeet, a non-loop version that wont blow your stack. Also useful starting point if you want to use the fork-join framework.
(Disclaimer: Not tested, not compiled, not sensible.)
Perhaps the best (single-threaded, no surrogate-pair support) way to write it:
The following source code will give you no.of occurrences of a given string in a word entered by user :-
Well, with a quite similar task I stumbled upon this Thread. I did not see any programming language restriction and since groovy runs on a java vm: Here is how I was able to solve my Problem using Groovy.
done.