Author: Lou Adler
How to get the number of occurrences of a substring within a string
Answer:
Answer 1:
I don't know of any existing code in Delphi to do this. If performance isn't
critical you can always use brute force. The following works but can easily be
improved:
1 function CountSubString(SubStr, St: string): integer;
2 var
3 i: integer;
4 begin
5 Result := 0;
6 for i := 1 to Length(st) do
7 if (copy(st, i, length(SubStr)) = SubStr) then
8 inc(Result);
9 end;
Answer 2:
While you can fiddle with the pos function and truncating the containing string
after each "find," I think the brute force method is easiest to code (untested):
10 function SubstrCount(sub, container: string): integer;
11 var
12 index: integer;
13 begin
14 result := 0;
15 for index := 1 to (length(container) - length(sub) + 1) do
16 if copy(container, index, length(sub)) = sub then
17 inc(result);
18 end;
If you need to skip over the found substring, say to count two occurrences of "AA"
within "AAAA" instead of three, change to:
19 function SubstrCount(sub, container: string): integer;
20 var
21 index: integer;
22 begin
23 result := 0;
24 index := 1;
25 while index <= (length(container) - length(sub) + 1) do
26 begin
27 if copy(container, index, length(sub)) = sub then
28 begin
29 inc(result);
30 index := index + length(sub);
31 end
32 else
33 inc(index);
34 end;
35 end;
Answer 3:
36 function SubStringCount(const str, substr: string): Integer;
37 var
38 start: integer;
39 begin
40 result := 0;
41 start := 0;
42 repeat
43 start := posex(substr, str, start + 1);
44 if (start = 0) then
45 break
46 else
47 inc(Result);
48 until
49 false;
50 end;
|