delphi - 如何使用注释对字符串列表进行排序

标签 delphi delphi-xe8

我有带有注释的字符串列表(如 Ini 文件部分内容):

;comment c
c=str1
;comment b
b=str2
;comment a
a=str3

任何如何按名称排序此列表的想法:

;comment a
a=str3
;comment b
b=str2
;comment c
c=str1

排序时对pair的评论应与pair链接

最佳答案

一种选择是将 TStringList 内容解析为第二个列表,该列表将名称、值和注释字符串分开并分组在一起,然后根据需要按名称对该列表进行排序,然后重新填充TStringList 以及已排序的组。例如:

uses
  ...
  System.Classes,
  System.SysUtils,
  System.Generics.Defaults,
  System.Generics.Collections,
  System.StrUtils,
  System.Types;

type
  ItemInfo = record
    LeadingText,
    Name,
    Value: string;
  end;

  ItemInfoComparer = class(TComparer<ItemInfo>)
  public
    function Compare(const Left, Right: ItemInfo): Integer; override;
  end;

function ItemInfoComparer.Compare(const Left, Right: ItemInfo): Integer;
begin
  if (Left.Name <> '') and (Right.Name <> '') then
    Result := AnsiCompareStr(Left.Name, Right.Name)
  else if (Left.Name <> '') then
    Result := -1
  else
    Result := 1;
end;

procedure SortMyList(List: TStringList);
var
  Compare: IComparer<ItemInfo>;
  Items: TList<ItemInfo>;
  Info: ItemInfo;
  I: Integer;
  InText: Boolean;
  S: String;
begin
  Compare := ItemInfoComparer.Create;
  Items := TList<ItemInfo>.Create(Compare);
  try
    Items.Capacity := List.Count;
    InText := False;

    for I := 0 to List.Count-1 do
    begin
      S := Trim(List[i]);
      if (S = '') or (S[1] = ';') then
      begin
        if InText then
          Info.LeadingText := Info.LeadingText + #13 + List[i]
        else
        begin
          Info.LeadingText := List[i];
          InText := True;
        end;
      end else
      begin
        Info.Name := List.Names[I];
        Info.Value := List.ValueFromIndex[I];
        Items.Add(Info);
        Info := Default(ItemInfo);
        InText := False;
      end;
    end;

    if InText then
      Items.Add(Info);

    Items.Sort;

    List.Clear;
    for I := 0 to Items.Count-1 do
    begin
      Info := Items[I];

      if Info.LeadingText <> '' then
      begin
        for S in SplitString(Info.LeadingText, #13) do
          List.Add(S);
      end;

      if Info.Name <> '' then
        List.Add(Info.Name + '=' + Info.Value);
    end;
  finally
    Items.Free;
  end;
end;

关于delphi - 如何使用注释对字符串列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31953735/

相关文章:

delphi - 如何更改 TRichEdit 中某些字符的颜色?

arrays - 清除组合框上的访问冲突

delphi - 如何获取TSynEdit等TWinControl的水平和垂直滚动条位置?

delphi - 哪些与指针相关的东西在 Delphi XE8 的移动编译器中不起作用?

delphi - 如何使用可变参数打印字符串?

delphi - 覆盖单个对象的选项卡控件

delphi - 通用整数的奇怪 PTypeInfo 名称

multithreading - 在全局异常处理程序中处理线程异常?

excel - OLE Excel 输出中的国际日期格式问题

listview - 检查当前是否在 Delphi VCL TListView 中显示编辑