Logo

Programming-Idioms

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

Idiom #82 Count substring occurrences

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

;;; s=str, t=pattern
(defun cnt_substr (str pattern)
  (loop for i from 0 to (- (length str) (length pattern) ) 
    sum (if (equal pattern (subseq str i (+ i (length pattern )))) 1  0 )))
#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