【发布时间】:2020-06-25 20:26:19
【问题描述】:
我需要计算字符串重复次数,然后按 DESC 对它们进行排序 示例:
字符串列表
111
222
333
111
222
111
我需要得到
111(3)
222(2)
333(1)
有人可以帮忙吗?
【问题讨论】:
-
您自己执行此操作时遇到什么具体问题?你为此做了哪些努力?
标签: delphi duplicates tstringlist
我需要计算字符串重复次数,然后按 DESC 对它们进行排序 示例:
字符串列表
111
222
333
111
222
111
我需要得到
111(3)
222(2)
333(1)
有人可以帮忙吗?
【问题讨论】:
标签: delphi duplicates tstringlist
使用TStringList 很容易做到这一点。根据需要先对其进行排序,然后循环遍历它,计算重复的字符串,例如:
var
List: TStringList;
Dups: TStringList;
I, Count: Integer;
StrToCompare, StrItem: string;
begin
List := TStringList.Create;
try
List.Add('111');
List.Add('222');
List.Add('333');
List.Add('111');
List.Add('222');
List.Add('111');
List.Sort; // or List.CustomSort() if needed
Dups := TStringList.Create;
try
StrToCompare := List[0];
Count := 1;
for I := 1 to List.Count-1 do
begin
StrItem := List[I];
if StrItem <> StrToCompare then
begin
Dups.Add(Format('%s(%d)', [StrToCompare, Count]));
StrToCompare := StrItem;
Count := 1;
end else
Inc(Count);
end;
Dups.Add(Format('%s(%d)', [StrToCompare, Count]));
// use Dups as needed...
finally
Dups.Free;
end;
finally
List.Free;
end;
end;
【讨论】: