How to save only a particular item in the tstringlist to a file

前端 未结 2 1112
星月不相逢
星月不相逢 2020-12-20 07:09

Here is my code.

var
  filehan : Textfile;
  i : Integer;
  LineOfText   : String;
  tsl : TStringList;
  Name, Emp_id : string;
begin
  stf := TStringList.c         


        
2条回答
  •  半阙折子戏
    2020-12-20 07:53

    Don't forget to reclaim the memory from tsl so it won't leak.

    It seems you're came from some garbage-collected language, lazy oen where u do not think about memory at all, like PHP or Python.

    So you'd better read Delphi help about objects and their life, or read some book liek Delphi Foundations.

    Until that... Variant 3: Since you seems not having the required skill to control and manage lifetime of objects, then use reference-counted types, like arrays or interfaces, for which Delphi controls their lifetime more or less.

    Elaborating from the answers from Split a string into an array of strings based on a delimiter you can draft few variants, for example:

    var sda: TStringDynArray; 
    begin
      sda := SplitString(LineOfText, ':' );
      Assignfile ( filehan2, 'FSTRING.txt');
      Rewrite ( filehand2 );
      try
        WriteLN (filehan2, sda[0]);   WriteLN (filehan2, sda[1]);
      finally
        CloseFile(filehan2);
      end;
    end;
    

    Okay - since you told you have old Delphi 7 - you do not have SplitString function there. But you can spare few minutes and make one. http://pastebin.ca/2309695

    You also can get helpful Jedi CodeLib library from http://jcl.sf.net

    var isl1, isl2: IJclStringList;
    begin
      isl1 := TJclStringList.Create;
         isl1.LoadFromFile('EMP.txt');
      isl2 := TJclStringList.Create.Split(isl1[0], ':');
      isl1.Clear.Add( [ isl2[0], isl2[1] ] ).SaveToFile('FSTRING.txt');
    end;   
    

    With the sample like 300: rani : joseph: 210: 500 : 700 it seems you have a lot of spaces around real data. Then you should trim those spaces off. Like WriteLN (filehan2, Trim( sda[0] )); or like isl1.Clear.Add( [ Trim( isl2[0] ),..... Read manuals about Trim function;


    If the line has the number 210

    Then check it, just with "if" statement;

    var isl1, isl2, isl3: IJclStringList; 
        EveryLine: string; i: integer;
    begin
      isl1 := TJclStringList.Create;
      isl2 := TJclStringList.Create;
      isl3 := TJclStringList.Create;
    
      isl1.LoadFromFile('EMP.txt');
    
    // for EveryLine in isl1 do begin 
    //    - this works in free Lazarus or modern Delphi, but not in D7 }
      for i := 0 to isl1.Count - 1 do begin;
          EveryString := isl1[i];
    
          isl2.Split(EveryString, ':').Trim;
          if isl2.Count >= 4 then // does 3rd element even exist ???
             if StrToIntDef( isl2[3], -1 ) = 210 then
                CallSomeProcedureToRetrieveMoreDetails; 
          isl3.Clear.Add( [ isl2[0], isl2[1] ] ).SaveToFile('FSTRING.txt');
      end; // for
    end;  // function
    

提交回复
热议问题