...count the number of occurrences of a substring within a string?

Author: Stefan Kellermann

Category: Strings

function CountPos(const subtext: string; Text: string): Integer;
begin
  if 
(Length(subtext) = 0) or (Length(Text) = 0) or (Pos(subtext, Text) = 0) then
    
Result := 0
  else
    
Result := (Length(Text) - Length(StringReplace(Text, subtext, ', [rfReplaceAll]))) div
      Length(subtext);
end;

 

printed from
www.swissdelphicenter.ch
developers knowledge base