Delphi: count number of times a string occurs in another string
function Occurrences(const Substring, Text: string): integer;
var
offset: integer;
begin
result := 0;
offset := PosEx(Substring, Text, 1);
while offset <> 0 do
begin
inc(result);
offset := PosEx(Substring, Text, offset + length(Substring));
end;
end;
One of the most clever ways I've ever seen to do this:
{ Returns a count of the number of occurences of SubText in Text }
function CountOccurences( const SubText: string;
const Text: string): Integer;
begin
if (SubText = '') OR (Text = '') OR (Pos(SubText, Text) = 0) then
Result := 0
else
Result := (Length(Text) - Length(StringReplace(Text, SubText, '', [rfReplaceAll]))) div Length(subtext);
end; { CountOccurences }
If you find yourself frequently searching occurences in a large body of text and performance becomes an issue, you could try the Boyer-Moore search algorithm.
the worst-case to find all occurrences in a text needs approximately 3n comparisons
An implementation in Delphi can be found at our very own SO here
I need three fast-on-large-strings functions: fast search, fast search and replace, and fast count of substrings in a string.