I need to know how many times a substring occurs in a given string. I figured that I might as well create an extension method:
public static int Occurences(this string str, string val)
{
string copy = str;
int instancesOf = 0;
int indexOfVal;
while ((indexOfVal = copy.IndexOf(val)) != -1)
{
copy = copy.Remove(indexOfVal, val.Count());
instancesOf++;
}
return instancesOf;
}
I'm not sure that the assignment in the while
loop is good practice. Should I change this to compute the value once outside the loop, and once in the loop, like this?
int indexOfVal = copy.IndexOf(val);
while (indexOfVal != -1)
{
copy = copy.Remove(indexOfVal, val.Count());
instancesOf++;
indexOfVal = copy.IndexOf(val);
}
Any and all comments appreciated, the more the better.
"bbb".Occurences("bb")
returns 1. \$\endgroup\$"bbb".Occurrences("bb")
return 1 or 2? \$\endgroup\$val
is long, and yourstr
is pathological, the running time could be O(n^2). To avoid that, you could use a smarter string-searching algorithm, such as the Z Algorithm, which works in O(n) time. \$\endgroup\$