Author: Ernesto De Spirito
A function that returns the number of times a substring occurs in a string. There's
also an ANSI version.
Answer:
The following functions return the number of occurrences of a char or a substring
within a string or ANSI string:
1 interface2 3 function Occurs(const str: string; c: char): integer; overload;
4 function Occurs(const str: string; const substr: string): integer;
5 overload;
6 function AnsiOccurs(const str: string; const substr: string): integer;
7 8 implementation9 10 uses sysutils;
11 12 function Occurs(const str: string; c: char): integer;
13 // Returns the number of times a character occurs in a string14 var15 p: PChar;
16 begin17 Result := 0;
18 p := PChar(Pointer(str));
19 while p <> nildo20 begin21 p := StrScan(p, c);
22 if p <> nilthen23 begin24 inc(Result);
25 inc(p);
26 end;
27 end;
28 end;
29 30 function Occurs(const str: string; const substr: string): integer;
31 // Returns the number of times a substring occurs in a string32 var33 p, q: PChar;
34 n: integer;
35 begin36 Result := 0;
37 n := Length(substr);
38 if n = 0 then39 exit;
40 q := PChar(Pointer(substr));
41 p := PChar(Pointer(str));
42 while p <> nildo43 begin44 p := StrPos(p, q);
45 if p <> nilthen46 begin47 inc(Result);
48 inc(p, n);
49 end;
50 end;
51 end;
52 53 function AnsiOccurs(const str: string; const substr: string): integer;
54 // Returns the number of times a substring occurs in a string55 // ANSI version56 var57 p, q: PChar;
58 n: integer;
59 begin60 Result := 0;
61 n := Length(substr);
62 if n = 0 then63 exit;
64 q := PChar(Pointer(substr));
65 p := PChar(Pointer(str));
66 while p <> nildo67 begin68 p := AnsiStrPos(p, q);
69 if p <> nilthen70 begin71 inc(Result);
72 inc(p, n);
73 end;
74 end;
75 end;
Copyright (c) 2001 Ernesto De Spiritomailto:edspirito@latiumsoftware.com
Visit: http://www.latiumsoftware.com/delphi-newsletter.php