Mega Code Archive

 
Categories / Delphi / Examples
 

Counting occurrences in a string

A function that returns the number of times a substring occurs in a string. There's also an ANSI version. Counting occurrences in a string The following functions return the number of occurrences of a char or a substring within a string or ANSI string: interface function Occurs(const str: string; c: char): integer; overload; function Occurs(const str: string; const substr: string): integer; overload; function AnsiOccurs(const str: string; const substr: string): integer; implementation uses sysutils; function Occurs(const str: string; c: char): integer; // Returns the number of times a character occurs in a string var p: PChar; begin Result := 0; p := PChar(Pointer(str)); while p <> nil do begin p := StrScan(p, c); if p <> nil then begin inc(Result); inc(p); end; end; end; function Occurs(const str: string; const substr: string): integer; // Returns the number of times a substring occurs in a string var p, q: PChar; n: integer; begin Result := 0; n := Length(substr); if n = 0 then exit; q := PChar(Pointer(substr)); p := PChar(Pointer(str)); while p <> nil do begin p := StrPos(p, q); if p <> nil then begin inc(Result); inc(p, n); end; end; end; function AnsiOccurs(const str: string; const substr: string): integer; // Returns the number of times a substring occurs in a string // ANSI version var p, q: PChar; n: integer; begin Result := 0; n := Length(substr); if n = 0 then exit; q := PChar(Pointer(substr)); p := PChar(Pointer(str)); while p <> nil do begin p := AnsiStrPos(p, q); if p <> nil then begin inc(Result); inc(p, n); end; end; end;