Delphi:计算字符串在另一个字符串中出现的次数

时间:2011-03-10 20:09:18

标签: string delphi delphi-2007

我正在使用Delphi 2007并想知道是否有一种简单的方法来计算字符串在另一个字符串中出现的次数。我可以使用任何内置函数吗?

示例:

  • “How”在字符串“你好吗?”中出现一次。
  • “do”在字符串“你好吗?”中出现两次。

5 个答案:

答案 0 :(得分:37)

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;

答案 1 :(得分:9)

我见过的最聪明的方法之一:

{ 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 }

答案 2 :(得分:4)

如果您发现自己经常在大型正文中搜索出现并且性能成为问题,那么您可以尝试使用Boyer-Moore search algorithm

  

查找所有事件的最坏情况   在文本中大约需要3n   比较

Delphi中的实现可以在我们自己的SO here

中找到
  

我需要三个快速大字符串   功能:快速搜索,快速搜索   并替换,快速计数   字符串中的子串。

答案 3 :(得分:1)


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;

答案 4 :(得分:0)

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