Logo

Programming-Idioms

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

Idiom #82 Count substring occurrences

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

sum [ 1 | r <- tails s, isPrefixOf t r ]

overlapping occurences of t in s are indeed found and counted
Data.List
length . filter (isPrefixOf t) . tails $ s

Implemented using mostly point free style. Overlapping occurrences are counted.
#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