none
searching string in substring RRS feed

  • Question

  • Hi,

     

    How can I  find out the number of times a substring appears in a string.

     

    Thanks,

    Thursday, December 15, 2005 3:21 PM

Answers

  • I can think of 2 ways right off the bat.  Here's some code that counts the number of angle-brackets in a XML string using Regular Expressions, and then just some simple iterating code:

    string myString = "<product><name>Prod1</name><price>248.74</price>"
       + "<fields><field><name>Shipping Cost</name>"
       + "
    <value>3.00</value></field></fields></product>";
       
    // method 1
    System.Text.RegularExpressions.MatchCollection mc 
        = System.Text.RegularExpressions.Regex.Matches(myString, "<");

    Console.WriteLine(mc.Count);

    // method 2
    int lastmatch = myString.IndexOf("<");
    int matches = 0;

    while (lastmatch != -1)
    {
       matches ++;
       lastmatch = myString.IndexOf("<", lastmatch + 1);
    }

    Console.WriteLine(matches);

    Thursday, December 15, 2005 3:52 PM