Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delphi: count number of times a string occurs in another string

Tags:

I'm using Delphi 2007 and wonder if there is a simple way of counting the number of times a string occurs in another string. Any builtin function I can use?

Examples:

  • "How" occurs once in the string "How are you?"
  • "do" occurs twice in the string "How do you do?"
like image 405
Jonas Avatar asked Mar 10 '11 20:03

Jonas


1 Answers

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; 
like image 91
Andreas Rejbrand Avatar answered Oct 01 '22 12:10

Andreas Rejbrand