【问题标题】:delphi - count duplicates in list and sort [closed]delphi - 计算列表中的重复项并排序[关闭]
【发布时间】:2020-06-25 20:26:19
【问题描述】:

我需要计算字符串重复次数,然后按 DESC 对它们进行排序 示例:

字符串列表

111
222
333
111
222
111

我需要得到

111(3)
222(2)
333(1)

有人可以帮忙吗?

【问题讨论】:

  • 您自己执行此操作时遇到什么具体问题?你为此做了哪些努力?

标签: delphi duplicates tstringlist


【解决方案1】:

使用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;

【讨论】:

    猜你喜欢
    • 2022-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-05
    • 2019-02-04
    • 2014-12-17
    • 1970-01-01
    相关资源
    最近更新 更多