我使用的是Delphi2007,我想知道是否有一种简单的方法来计算一个字符串在另一个字符串中出现的次数。有没有我可以使用的内置函数?
示例:
发布于 2011-03-11 04:14:53
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;
发布于 2011-03-11 11:59:06
这是我见过的最聪明的方法之一:
{ 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 }
发布于 2014-07-16 05:18: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;
https://stackoverflow.com/questions/5265317
复制相似问题