Logo

Programming-Idioms

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

Idiom #82 Count substring occurrences

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

my $t="banana bo bana bandana";

my $c =()= $t=~ m/ana/g;
print "count without overlap: $c\n";

$c =()= $t =~ m/an(?=a)/g;
print "count with overlap: $c\n";

The =()= operator makes the match operate in list context (http://www.perlmonks.org/?node_id=527973), and the (?=) operator allows it to match overlapping text (surround the part that can overlap).
#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