Jonas
Jonas

Reputation: 4263

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

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:

Upvotes: 22

Views: 25838

Answers (6)

Anse
Anse

Reputation: 1660

Newer Delphi versions have a CountChar string helper, counting occurrences of a single character in a string:

var
  MyText: String;
begin
  MyText := 'How are you?';
  ShowMessage(MyText.CountChar('o').ToString);
end;

Upvotes: 2

guest
guest

Reputation: 11

function stringcount(pBefore: String; pSubstring: String; pFlags: TReplaceFlags): Integer;
begin
  result:= round((pBefore.Length - stringreplace(pBefore, pSubstring, '', pFlags).Length) / pSubstring.Length);
end;

Upvotes: 1

GoodMan
GoodMan

Reputation: 9


uses
  StrUtils;    

function Occurrences(const Substring, Text: string;
  const ignoreUppercase: Boolean = false): Integer;
var
  inSubstring, inText: string;
  inPos: Integer;
begin
  Result:= 0;

  if (Substring = '') or (Text = '') then
    Exit;

  if ignoreUppercase then
  begin
    inSubstring:= AnsiLowerCase(Substring);
    inText:=  AnsiLowerCase(Text);
  end
  else
  begin
    inSubstring:= Substring;
    inText:=  Text;
  end;

  inPos:= 1;

  repeat
    inPos:= posEx(inSubstring, inText, inPos);
    if inPos > 0 then
    begin
      Inc(Result);
      inPos:= inPos + Length(inSubstring);
    end;
  until inPos = 0;
end;

Upvotes: 0

Lieven Keersmaekers
Lieven Keersmaekers

Reputation: 58491

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.

Upvotes: 4

RobertFrank
RobertFrank

Reputation: 7394

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 }

Upvotes: 12

Andreas Rejbrand
Andreas Rejbrand

Reputation: 109003

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;

Upvotes: 41

Related Questions