The following code works fine removing correct duplicated lines, but when i show I
before remove the line of StringList is displayed correctly the index (I
) only of the first ocurrence of duplicated, after, the index is showed wrong not corresponding to correct (always minor than real index). How fix it?
This is the code:
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.
If removing duplicates with higher indices don't violate your rules, just make outer loop downward. In this case removing preserves the rest.
for I := Pred(slSrc.Count) downto 0 do
begin
for J := 0 to I - 1 do
...
slSrc.Delete(I);