A simple way of counting the number of times a string occurs in another string in Delphi. For an example, “of” occurs twice in “How to count the number of occurrences of a string” where as “within” occurs once in “SubString occurrences within a string”.
The below function will return the number of occurrences of a string within another string. You can use the below function to count occurrences of a substring.
function CountOfStringOccurrences(const SubStr, s: string): integer; var offset: integer; begin result := 0; offset := PosEx(SubStr, s, 1); while offset 0 do begin inc(result); offset := PosEx(SubStr, s, offset + length(SubStr)); end; end;