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

前端 未结 5 1233
野性不改
野性不改 2020-12-10 10:49

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?

Example

相关标签:
5条回答
  • 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 }
    
    0 讨论(0)
  • 2020-12-10 11:27
    
    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;
    
    
    0 讨论(0)
  • 2020-12-10 11:30

    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.

    0 讨论(0)
  • 2020-12-10 11:31
    function stringcount(pBefore: String; pSubstring: String; pFlags: TReplaceFlags): Integer;
    begin
      result:= round((pBefore.Length - stringreplace(pBefore, pSubstring, '', pFlags).Length) / pSubstring.Length);
    end;
    
    0 讨论(0)
  • 2020-12-10 11:40
    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;
    
    0 讨论(0)
提交回复
热议问题