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

Jon*_*nas 21 delphi string delphi-2007

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

例子:

  • 字符串"How are you?"中出现一次"how"
  • "do"在字符串"你好吗?"中出现两次.

And*_*and 38

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;
Run Code Online (Sandbox Code Playgroud)

  • 第二个PosEx可以写成"offset:= PosEx(SubString,Text,offset + length(SubString));"如果你不关心重复的子串.;) (2认同)
  • +1 我可能会使用 var 并在其中存储 SubString 的长度以避免重复调用 Length,但由于 Length 实际上只从 @SubString 读取负偏移量,因此无论如何它可能不会对性能造成太大影响。:) (2认同)

Rob*_*ank 10

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

{ 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 }
Run Code Online (Sandbox Code Playgroud)

  • 聪明但缓慢,并且浪费内存。 (2认同)