Finding occurance of a substring in a string in C# 
Author Message
 Finding occurance of a substring in a string in C#

How can find the number of occurances of a particular substring in a string in C#?


Sat, 05 Feb 2005 06:27:22 GMT  
 Finding occurance of a substring in a string in C#
You have to loop, using IndexOf to find the next instance... As best I know
there is no CountOf function - you have to write your own.


Quote:
> How can find the number of occurances of a particular substring in a

string in C#?


Sat, 05 Feb 2005 07:23:36 GMT  
 Finding occurance of a substring in a string in C#
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;
                }



Mon, 07 Feb 2005 02:27:17 GMT  
 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;
> }



Mon, 07 Feb 2005 06:58:19 GMT  
 
 [ 4 post ] 

 Relevant Pages 

1. strstr or strspn for finding a substring

2. Finding a substring inside a CString

3. Getting Substring from String.LastIndexOf

4. how to check that string contains substring?

5. Searching string for substring question

6. How to do substring function for C string

7. longest substring in a string

8. How to remove a substring from a string

9. How to insert a substring in a string?

10. substring in a string

11. about searchin' substring in a string

12. How can I extract the substring of string??

 

 
Powered by phpBB® Forum Software