Search code examples
c#split-function

Split function in c#


I have a program which accepts a url(example:care.org), gets the page source of the url and does some calculation.

  string text = <the page source of care.org>
  string separator = "car";
  var cnt = text.ToLower().Split(separator,StringSplitOptions.None);

My aim is to count the number of occurence of the "car" in the page source, My code considers care as 'car'|'e' it splits it this way.. But i want it to consider whole seperator as one and do the splittin

Please help me with this


Solution

  • You should use reular expressions instead of split() method:

    Regex regex = new Regex(@"\bcar\b"); // you should modify it if `car's` needed
    
    Match match = regex.Match(text);
    int cnt = 0;
    
    while (match.Success)
    {
       cnt++;
       match = match.NextMatch();
    }
    
    // here you get count of `car` in `cnt`