Logo

Programming-Idioms

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

Idiom #82 Count substring occurrences

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

uses strutils;
function Count(t, s: String): Integer;
var
  Offset, P: Integer;
begin
  Result := 0;
  Offset := 1;
  P := PosEx(t, s, Offset);
  while P > 0 do
  begin
    Inc(Result);
    P := PosEx(t, s, P + 1);
  end;
end;

Strings in Pascal start at index 1, therefore Offset is set to 1.
The function counts overlapping occurrences.
#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