Delphi TStringList删除重复项


本文整理自网络,侵删。

 
有一个文本1.txt,里面内容例如下:
11
22
33
22
44
11
55
...
N个

处理后的想要结果是这样:
33
44
55
...
N个

但是用以下代码处理并不是这样子,它保留了一个重复。
  pList := TStringList.Create;
  pList.sorted := True;
  pList.Duplicates := dupIgnore;
  pList.LoadFromFile('1.txt');
  pList.SaveToFile('2.txt');
  pList.Free;
结果为:
11
22
33
44
55
...
N个


 procedure RemoveDuplicates(const stringList : TStringList) ;
 var
   buffer: TStringList;
   cnt: Integer;
 begin
   stringList.Sort;
   buffer := TStringList.Create;
   try
     buffer.Sorted := True;
     buffer.Duplicates := dupIgnore;
     buffer.BeginUpdate;
     for cnt := 0 to stringList.Count - 1 do
       buffer.Add(stringList[cnt]) ;
     buffer.EndUpdate;
     stringList.Assign(buffer) ;
   finally
     FreeandNil(buffer) ;
   end;
 end;



var
  sLi: TStringList;
begin
  sLi := TStringList.Create;
  try
    sLi.LoadFromFile('c:\111.txt');
    RemoveDuplicates(sLi);
    sLi.SaveToFile('c:\111.txt');
  finally
    sLi.Free;
  end;
end;

删除重复项,并且不保留代码如下:


procedure GetUniqueStringList;
var
  CurrentString: string;
  LastString: string;
  Count: Integer;
  Index: Integer;
  SourceList: TStringList;
  UniqueList: TStringList;
begin
  Count := 1;
  LastString := '';
  SourceList := TStringList.Create;
  UniqueList :=  TStringList.Create;
  try
    SourceList.LoadFromFile('1.txt');
    SourceList.Sorted := True;
    for Index :=0 to Pred(SourceList.Count) do
    begin
      CurrentString := SourceList[Index];
      if CurrentString = LastString then
        Count := Count + 1
      else
      begin
        if LastString <> '' then
        begin
          if Count = 1 then
            UniqueList.Add(LastString)
          else
            Count := 1;
        end;
      end;
      LastString := CurrentString;
    end;
    if Count = 1 then UniqueList.Add(LastString);
    UniqueList.SaveToFile('2.txt');
  finally
    SourceList.Free;
    UniqueList.Free;
  end;
end;

来源:https://bbs.csdn.net/topics/390463304

相关阅读 >>

Delphi判断文件是否正在被使用

Delphi 网上获取北京时间xmlhttprequest如何访问需要安全验证的网站

Delphi 实现卸载windows应用程序(类似360软件管家-卸载程序)

Delphi inttohexansi

Delphi windows 编程[20] - 改变菜单项并换行

Delphi的with…do语句的用法

Delphi tms web core js callproc

Delphi winapi: setwindowtext - 设置窗口标题

Delphi如何获取qq2010聊天窗口句柄

Delphi xe6 使用intent启动活动并在android应用程序中获取返回值的示例

更多相关阅读请进入《Delphi》频道 >>



打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...