You are here

Count number of times a string occurs in another string in Delphi

Submitted by Asif Nowaj, Last Modified on 2019-11-22

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;

Discussion or Comment

If you have anything in mind to share, please bring it in the discussion forum here.

https://forum.everyething.com/delphi-f39/