Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using linq to count substrings in a string?

Tags:

c#

linq

I could use the following linq expression to count the number of occurrences of a word as follows:

string test = "And And And";
int j = test.Split(' ').Count(x => x.Contains("And"));

However what if I was searching for "And And", Is there a way to use linq to count words without using split. Do any of these methods take longer the O(n)?

like image 679
SamFisher83 Avatar asked Feb 04 '12 20:02

SamFisher83


2 Answers

You can use a regular expression:

string test = "And And And";
int j = Regex.Matches(test, "And").Cast<Match>().Count();

BTW, do you want to allow overlapping occurrences? i.e. if you're looking for "And And", do you consider that test contains 1 or 2 occurrences of it?

like image 93
Thomas Levesque Avatar answered Sep 25 '22 11:09

Thomas Levesque


I found a clever solution that can be resolved serverside with most LINQ to ORMs:

string search = "foo";
int searchLength = search.Length;

var result = qry.Select(i => new { Object = i, Occurrences = (i.SomeProperty.Length - i.SomeProperty.Replace(search, "").Length) / searchLength });

The idea is to replace the substring by an empty string and then divide the difference in string length by the length of the search term.

like image 41
Marco Avatar answered Sep 23 '22 11:09

Marco