
Finding occurance of a substring in a string in C#
Your routine had some odd properties - unless your needs were different from
just finding the number of distinct ocurrances of a substring in a string,
the following might work better...
public int CountDistinctIndexesOf(string substring, string value)
{
int count = 0;
int foundAtIndex;
int searchFromIndex = 0;
while((foundAtIndex = value.IndexOf(substring, searchFromIndex)) != -1)
{
searchFromIndex = foundAtIndex + substring.Length;
count++;
}
return count;
Quote:
}
Quote:
> This is a little code which I wrote to solve my own problem.
> Feel free to use this in case anybody needs it.
> public int GetSubstringCount( string passSubstring, string passString )
> {
> int holdFound = 0;
> for ( int i = 0; i < passString.Length ; i++ )
> {
> if ( passString.IndexOf( passSubstring, i ) > 0)
> {
> i = i + passSubstring.Length;
> holdFound += 1;
> }
> }
> return holdFound;
> }