Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • C#

Idiom #82 Count substring occurrences

Find how many times string s contains substring t.
Specify if overlapping occurrences are counted.

int SubstringCount(string s, string t, bool allowOverlap = false)
{
  int p = 0;
  int tl = allowOverlap ? 1 : t.Length;
  int cnt = 0;

  while (1 == 1)
  {
    p = s.IndexOf(t, p);
    if (p == -1) break;
    p += tl;
    cnt++;
  }
  return cnt;
}

Optional third argument can be set to true to allow overlapping occurences
#include <string.h>
unsigned n;
for (n = 0; s = strstr(s, t); ++n, ++s)
	;

Overlapping occurrences are counted.
This destroys the pointer s.

New implementation...
< >
deleplace