Hi,
I'm trying to write an in-line function for count occurrences of a word in a string using lambda expressions recursively.
The function:
Func<string, string, int> getOccurrences = null;
getOccurrences = (text, searchTerm) =>
text.IndexOf(searchTerm, StringComparison.OrdinalIgnoreCase) == -1
? 0
: getOccurrences(
text.Substring(
text.IndexOf(searchTerm, StringComparison.OrdinalIgnoreCase)
+ searchTerm.Length),
searchTerm) + 1;
The problem is that I'm call IndexOf
method twice,
The first one is for recursive break condition and the second one is to get the value for add it.
Is there any suggest to call it once?
Thanks in advance.