0

I have a string, for example "This is an example." and in this sentece is another words - "a little test". I would like to know how many times is "a little test" in the sentence. Is there any way? Thanks

string tmp = "This a little test is a little test an example. a little test";
int sum = ...... (the count of "a little test")
Lubos Marek
  • 178
  • 1
  • 3
  • 13
  • 6
    Possible duplicate of [How would you count occurrences of a string within a string?](http://stackoverflow.com/questions/541954/how-would-you-count-occurrences-of-a-string-within-a-string) – hellow Mar 30 '16 at 09:03
  • @cookiesoft although the title of the referred question may imply otherwise, the actual question (and accepted answer) is for ocurrences of a single character in a string, which is not what the OP is asking – Jcl Mar 30 '16 at 09:06
  • Please see ["Should questions include “tags” in their titles?"](http://meta.stackexchange.com/questions/19190/should-questions-include-tags-in-their-titles), where the consensus is "no, they should not"! –  Mar 30 '16 at 09:13

1 Answers1

6

You could do something like:

int sum = Regex.Matches(tmp, "a little test").Count;

Check it in a fiddle

If your "search term" may contain characters that could be used in a regular expression, you may want to use Regex.Escape:

int sum = Regex.Matches(tmp, Regex.Escape(@"my search term with $pecia| $ymb\0Ls")).Count;
Jcl
  • 27,696
  • 5
  • 61
  • 92
  • 1
    Brilliant. +1. Also (for further reading): http://cc.davelozinski.com/c-sharp/c-net-fastest-way-count-substring-occurrences-string –  Mar 30 '16 at 09:09