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. – mjolka Mar 29 at 23:57"bbb".Occurrences("bb")
return 1 or 2? – nhgrif Mar 30 at 0:00val
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. – 200_success♦ Mar 30 at 1:05