Logo

Programming-Idioms

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

Idiom #82 Count substring occurrences

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

let n = 0 // the number of occurences
let acc = s
let i
while ((i = acc.indexOf (t)) + 1) {
  n++
  acc = acc.slice (i + 1)
}

Overlapping occurences are counted.
There's no builtin but at least JavaScript isn't friggin' Pascal.
#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