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 unigui确认对话框

Delphi tscreen 类 - 通过 screen 更换光标

Delphi汉字与多字节编码的转换

Delphi从路径中分离文件名

Delphi win7下超级管理员创建普通权限任务

Delphi dbgrids 组件内实现查询

Delphi 获取文件夹时间

Delphi 设置richedit的行间距

Delphi 2009 之 tedit 加强的功能

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



打赏

取消

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

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

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

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

评论

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

    正在狠努力加载,请稍候...