MKaiser
MKaiser

Reputation: 45

Delphi : Copy specific lines from Stringlist to another

I'm getting an "Index limit out of bonds" error when I try to copy specific strings by index from one TStringList to another.

I have a text file that contain lines formatted with a pipe "|" delimiter. It looks like this:

test.txt file

In my destination file, I want to copy only some items from lines that start with '3M', in order to get something like this (the first line, for example):

3M 2189300002 12.99

3M is Stringlist.strings[1]

2189300002 is Stringlist.strings[3]

12.99 is Stringlist.strings[6]

Here is my code:

var
  sl,new : tstringlist;
  lscount,index : integer;
begin
  sl:= TStringList.Create;
  sl.LoadFromFile('C:\Folder\test.txt');

  new := tstringlist.create;

  lscount :=  lstringlist.Count;

  for index := 0 to lscount do
  begin
    sl.delimiter := '|';
    sl.StrictDelimiter := True;

    sl.DelimitedText := sl.Strings[index];

    if sl.Strings[1] = '3M' then
      new.Add(sl.Strings[1]+sl.Strings[3]+sl.Strings[6]);

  end;

  new.SaveToFile('C:\Folder\new.txt');
  sl.Free;
  new.Free

end;

What's wrong with my code?

Upvotes: 0

Views: 2303

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 596988

There are quite a number of mistakes in your code.

Your for loop is looping from index 0 to lscount, but the upper bound of the TStringList is lscount-1 instead.

You are modifying sl while you are looping through sl. You need to use a separate TStringList when parsing each line.

You are accessing the parsed strings using 1-based indexes, but TStringList uses 0-based indexes instead.

Try something more like this:

var
  sl, parse, new : TStringList;
  index : Integer;
begin
  sl := TStringList.Create;
  try
    sl.LoadFromFile('C:\Folder\test.txt');

    new := TStringList.create;
    try
      parse := TStringList.Create;
      try
        parse.Delimiter := '|';
        parse.StrictDelimiter := True;

        for index := 0 to sl.Count-1 do
        begin
          parse.DelimitedText := sl.Strings[index];

          if (parse.Count > 5) and (parse.Strings[0] = '3M') then
            new.Add(parse.Strings[0] + ' ' + parse.Strings[2] + ' ' + parse.Strings[5]);
        end;
      finally
        parse.Free;
      end;

      new.SaveToFile('C:\Folder\new.txt');

    finally
      new.Free;
    end;
  finally
    sl.Free
  end;
end;

Upvotes: 2

Related Questions