【问题标题】:Delphi : Copy specific lines from Stringlist to anotherDelphi:将特定行从Stringlist复制到另一个
【发布时间】:2017-10-03 20:59:51
【问题描述】:

当我尝试按索引将特定字符串从一个 TStringList 复制到另一个时,出现“键的索引限制”错误。

我有一个文本文件,其中包含用管道“|”格式化的行分隔符。它看起来像这样:

在我的目标文件中,我只想复制以'3M' 开头的行中的一些项目,以便获得类似的内容(例如第一行):

3M 2189300002 12.99

3MStringlist.strings[1]

2189300002Stringlist.strings[3]

12.99Stringlist.strings[6]

这是我的代码:

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;

我的代码有什么问题?

【问题讨论】:

    标签: text delphi-xe5 tstringlist


    【解决方案1】:

    你的代码有很多错误。

    您的 for 循环从索引 0 循环到 lscount,但 TStringList 的上限改为 lscount-1

    在循环通过 sl 时,您正在修改 sl。解析每一行时需要使用单独的TStringList

    您正在使用基于 1 的索引访问已解析的字符串,但 TStringList 使用基于 0 的索引。

    试试这样的:

    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;
    

    【讨论】:

    • 这个问题对我来说是一个闪回,你的回答比我的要完整得多。
    猜你喜欢
    • 2013-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-06
    • 1970-01-01
    • 2016-04-10
    • 1970-01-01
    相关资源
    最近更新 更多