Reading txt file with multiple columns to insert into TListView

4

I have the following function:

var
   Colunas : TStringlist;
   Item: TListItem;
begin
   Colunas := TStringlist.Create;
   Colunas.Text := StringReplace('00:46:30@21/08/2014@Carlos dos Santos@São Paulo',
      '@',Char(13)+Char(10),[rfReplaceAll]);
   Item := LV.Items.Add;
   Item.SubItems.Add(Colunas[0]);
   Item.SubItems.Add(Colunas[1]);
   Item.SubItems.Add(Colunas[2]);

It separates by columns using the @ delimiter, in which case I put it manually. But, I have a file called client.txt and inside it there are several lines of type:

  

00: 46: 30 @ 21/08/2014 @ Carlos dos Santos @ São Paulo
    00: 46: 30 @ 21/08/2014 @ João da Silva @ São Paulo

How can I read this file, using the same function above and put everything inside a LISTVIEW?

Related: Explode in Delphi

    
asked by anonymous 29.08.2014 / 17:21

2 answers

6

I relied on a SOAN response to propose a way to read a file directly in a TStringlist , since the list can already be accessed "exploded" (using indexes).

var
  Linhas: TStringList;    

...

  Linhas := TStringList.Create;
  try
    Linhas.LoadFromFile(FileName);
    //Agora basta acessar as linhas com Linhas[0], Linhas[1], ..., Linhas[Linhas.Count-1]

  finally
    Linhas.Free;
  end;


Applying the solution to your .txt:

var
  Linhas:  TStringList;
  Colunas: TStringList;
  i:       integer;    

...

  Linhas := TStringList.Create;
  Colunas := TStringlist.Create;
  Colunas.Delimiter := '@';
  Colunas.StrictDelimiter := True;

  try
    Linhas.LoadFromFile( 'cliente.txt' );

    for i := 0 to Linhas.Count-1 do 
    begin
       Colunas.DelimitedText := Linhas[i];
       Item := LV.Items.Add;
       Item.SubItems.Add(Colunas[0]);
       Item.SubItems.Add(Colunas[1]);
       Item.SubItems.Add(Colunas[2]);
    end;

  finally
    Linhas.Free;
  end;

As pointed out by @Edgar Muniz Berlinck , the code has been improved by using the TStringList feature itself to to "explode" the string (and improved with help from @ Captcha , which reminded you of D2006 + StrictDelimiter):

We exchange:

       Colunas.Text := StringReplace(Linhas[i],'@',Char(13)+Char(10),[rfReplaceAll]);

By:

       Colunas.Delimiter := '@';
       Colunas.StrictDelimiter := True;
       ...
       Colunas.DelimitedText := Linhas[i];
    
29.08.2014 / 17:25
2

. You can use the following code to do this.

That way it gets more elegant is efficient.

procedure TForm1.Button1Click(Sender: TObject);
var
  Coluna, Linha: string;
  Colunas: TArray<string>;
begin
  Linha:= '00:46:30@21/08/2014@João da Silva@São Paulo';

  Colunas:= Linha.Split( [ '@' ] );

  for Coluna in Colunas do
    ShowMessage( Coluna );
end;

Split is a Helper of data type string . link

There are other methods Helper in data type string . Type Ctrl + Espaço after the variable to see the other methods.

    
29.08.2014 / 18:40