从文件工作中删除重复的行,但不显示正确的索引
Remove duplicated lines from file working, but not displaying correct index
以下代码可以很好地删除正确的重复行,但是当我在删除 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);
以下代码可以很好地删除正确的重复行,但是当我在删除 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);