gpt4 book ai didi

delphi - 计算备忘录中的特定文本(Delphi)

转载 作者:行者123 更新时间:2023-12-02 05:35:04 24 4
gpt4 key购买 nike

我有一个备忘录,里面有很多“芒果”行,我想计算它找到文本“芒果”的次数。

var
f, mango: Integer;
begin
mango := 0;
for f := 0 to m0.lines.Count - 1 do
begin
if AnsiContainsStr(m0.lines[f], 'mango') then
begin
mango := mango + 1;
m0.lines.Add(IntToStr(mango));
end
end;
end;

但是,例如,如果发现六个“芒果”条目,结果将如下所示:

1
2
3
4
5
6

我怎样才能得到结果只有6?

最佳答案

如果您只想在备忘录中显示总数,那么您需要执行以下操作:

var
f, mango: Integer;
begin
mango := 0;
for f := 0 to m0.lines.Count - 1 do
begin
if AnsiContainsStr(m0.lines[f], 'mango') then
begin
mango := mango + 1;
end
end;
m0.lines.Add(IntToStr(mango)); // This line needs to be outside of your loop
end;

每次增加计数时,您都会将其添加到列表中。

如果你想要一个可重用的函数,你可以使用这样的东西:

function CountStringListTexts(const ASearchList: TStrings; const ASearchText: string): Integer;
var
f: Integer;
begin
Result := 0;
for f := 0 to ASearchList.Count - 1 do
begin
if AnsiContainsStr(ASearchList[f], ASearchText) then
begin
Result := Result + 1;
end
end;
end;

要使用它,您可以执行以下操作:

m0.lines.Add(IntToStr(CountStringListTexts(m0.Lines, 'mango')));

这也可以制作成类助手:

type
TSClassHelper = class helper for TStrings
function CountMatchTexts(const ASearchText: string): Integer;
end;

function TSClassHelper.CountMatchTexts(const ASearchText: string): Integer;
var
f: Integer;
begin
Result := 0;
for f := 0 to Self.Count - 1 do
begin
if AnsiContainsStr(Self.Strings[f], ASearchText) then
begin
Result := Result + 1;
end
end;
end;

使用它会非常容易。你只需这样做:

m0.lines.Add(IntToStr(m0.Lines.CountMatchTexts('mango')));

关于delphi - 计算备忘录中的特定文本(Delphi),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23453100/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com