以下代码可以很好地删除正确的重复行,但当我在删除StringList的行之前显示I
时,索引(I
(仅显示第一个重复行的索引,之后,索引显示错误而与正确行不对应(总是比实际索引小(。如何修复?
这是代码:
program Project1;
{$APPTYPE CONSOLE}
{$R *.res}
uses
System.Classes,
System.SysUtils;
var
slSrc, slDup: TStringList;
I, J: Integer;
begin
try
slDup := TStringList.Create;
try
slSrc := TStringList.Create;
try
slSrc.LoadFromFile('C:src.txt');
for I := 0 to Pred(slSrc.Count) do
begin
for J := Pred(slSrc.Count) downto I + 1 do
begin
if SameStr(slSrc[I], slSrc[J]) then
begin
// Ex; If 1º dup index is = 3, is showed 3. OK
// If 2º dup index is = 15, is showed always a minor like 13 for example
// and continue displaying wrong index for next dups
Writeln(IntToStr(I) + ' : ' + slSrc[I]);
slDup.Add(slSrc[I]);
slSrc.Delete(I);
end;
end;
end;
slSrc.SaveToFile('C:src.txt');
slDup.SaveToFile('C:dup.txt');
finally
slSrc.Free;
end;
finally
slDup.Free;
end;
except
on E: Exception do
Writeln(E.ClassName, ': ', E.Message);
end;
Readln;
end.
如果删除索引较高的重复项不会违反规则,只需向下进行外循环即可。在这种情况下,删除会保留其余部分。
for I := Pred(slSrc.Count) downto 0 do
begin
for J := 0 to I - 1 do
...
slSrc.Delete(I);