Question

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

Was it helpful?

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`

OTHER TIPS

This is how can achieve what you want by using RegularExpressions:

string text = "the page source of care.org";
string separator = @"\bcar\b";
MatchCollection resultsarray = Regex.Matches(text, separator);

Now resultsarray contains your matches. You can count it using

resultsarray.Count

Split returns a string array, you could just count the results.

var cnt = text.ToLower().Split(separator,StringSplitOptions.None).count;

I dont think you need to split, since you are not going to do anything with the substring. You only want a count, so look in to using RegEx.Matches(text, "car[^a-zA-Z0-9]") or similar to define the patterns you are interested in. Good luck!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top