首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Delphi:计算一个字符串在另一个字符串中出现的次数

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

Stack Overflow用户
提问于 2011-03-11 04:09:18
回答 4查看 22.1K关注 0票数 22

我使用的是Delphi2007,我想知道是否有一种简单的方法来计算一个字符串在另一个字符串中出现的次数。有没有我可以使用的内置函数?

示例:

  • "How“在字符串"How are you?”中出现一次,
  • “do”在字符串“How do you do?”中出现两次
EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2011-03-11 04:14:53

代码语言:javascript
复制
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;
票数 40
EN

Stack Overflow用户

发布于 2011-03-11 11:59:06

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

代码语言:javascript
复制
{ 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 }
票数 11
EN

Stack Overflow用户

发布于 2014-07-16 05:18:27

代码语言:javascript
复制
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;
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5265317

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档