4

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)?

4
  • 2
    The code you posted doesn't compile... Do you mean int j = test.Split(' ').Count(x => x == "And");? Commented Feb 4, 2012 at 20:18
  • Where is the linq expression in your code? Commented Feb 4, 2012 at 20:23
  • @Peri the Count extension method is the linq portion of the given expression. Commented Feb 4, 2012 at 23:16
  • Im not sure this is LINQ. LINQ is 'from x select something' and that is translated to Extension methods calls. Commented Feb 5, 2012 at 0:13

4 Answers 4

7

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?

Sign up to request clarification or add additional context in comments.

5 Comments

@Peri, it's because MatchCollection implements the non-generic IEnumerable, but not IEnumerable<Match>, and Count only works on the generic version.
Don't forget to escape special regex characters if the string that you're looking for could contain them.
@Thomas: Don't know why but I was sure Matches returns an array of Match.
Never though of the case of two occurrences, but I guess it would be.
+1 for explaining the need for the Cast. Thanks @ThomasLevesque
1

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.

Comments

0

You can use IndexOf:

string what = "And";
int count = 0;
int pos = -what.Length;
for (;;)
{
    pos = input.IndexOf(what, pos + what.Length);
    if (pos == -1) break;
    count++;
}

1 Comment

Your answer is not using LINQ. OP is looking for a LINQ query.
0

This is not quite Linq, but you can also make an extension method like below. It is probably more efficient than any Linq solution:

        public static int CountSubStrings(this string input, string delimiter, bool ignoreCase = false)
    {
        int instancesNo = 0;
        int pos = 0;
        while((pos = input.IndexOf(delimiter, pos, ignoreCase ? StringComparison.InvariantCultureIgnoreCase : StringComparison.InvariantCulture)) != -1)
        {
            pos += delimiter.Length;
            instancesNo++;
        }
        return instancesNo;
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.