String.Contains Count?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • ceestand
    New Member
    • Mar 2007
    • 8

    String.Contains Count?

    Can anyone point me in the direction of functionality that will provide the number of times a String contains a given substring? Preferably in C# and/or built in to the .Net framework...
  • Plater
    Recognized Expert Expert
    • Apr 2007
    • 7872

    #2
    There's probably a better way to do this (Such as the overloads for .IndexOf()... ) but whatever.
    Code:
    string n="freddrandr";
    
    int count=0;
    for(int i=0;i<n.length;i++)
    {
       if (n.SubString(i).StartsWith("dr"))
       {
          count++;
       } 
    }
    //count will be 2

    Comment

    • ceestand
      New Member
      • Mar 2007
      • 8

      #3
      Thanks for your help.

      Comment

      • ceestand
        New Member
        • Mar 2007
        • 8

        #4
        For anyone interested, this is what I ended up using:
        public Int32 ContainsCount(S tring SearchPhrase, String SearchText) {
        String Remains = SearchText;
        Int32 NewIndex = 0;
        Int16 Count = 0;
        while (Remains.Length >= SearchPhrase.Le ngth)
        {
        NewIndex = Remains.IndexOf (SearchPhrase);
        if (NewIndex >= 0)
        {
        Count++;
        Remains = Remains.Substri ng(NewIndex + SearchPhrase.Le ngth);
        }
        else
        {
        return Count;
        }
        }
        return Count;
        }

        Comment

        Working...