delphi 怎么把TXT里面的内容逐行分割读取到listview里面。

2024-12-02 14:23:25
推荐回答(2个)
回答1:

procedure TForm1.Button2Click(Sender: TObject);
var
result_txt, save_txt : tstrings;
substr, str : String;
i, j, sub_i1, sub_i2 : Integer;
begin
result_txt := tstringlist.Create;
result_txt.LoadFromFile(ExtractFilePath(application.ExeName)+'result.txt');

save_txt := tstringlist.Create;

substr := '|'; //张三|80分|数学
for i:=0 to result_txt.Count-1 do
begin
str := result_txt[i];
sub_i1 := 0;
save_txt.Clear;
while pos(substr,str)>0 do
begin
sub_i2 := pos(substr,str);
save_txt.Add(copy(str,sub_i1+1,sub_i2-(sub_i1+1)));
str := copy(str,pos(substr,str)+1,length(str)-pos(substr,str)+1);
end;
save_txt.Add(str);

with lv_result.Items.Add do
begin
Caption := save_txt[0];
for j:=1 to save_txt.Count-1 do
begin
lv_result.Items[i].SubItems.Add(save_txt[j]);
end;
end;
end;

save_txt.Free;
result_txt.Free;
end;

列数不限,查找无限制,即只要是“|”为分隔符的都可以找到。
另外: HJ_3000 的答案有 BUG,如果内容含有空格的话,就找不到了。

回答2:

procedure TForm1.FormCreate(Sender: TObject);
Var
alist, blist: TStringlist;
I, J: Integer;
begin
alist := TStringlist.Create;
blist := TStringlist.Create;
try
alist.LoadFromFile('g:\a.txt');
for I := 0 to alist.Count - 1 do
begin
blist.Delimiter := '|';
blist.DelimitedText := alist[I];
if blist.Count = 3 then
begin
with ListView1.Items.Add Do
begin
caption := blist[0];
subitems.Add(blist[1]);
subitems.Add(blist[2]);
end;
end;
end;
finally
blist.Free;
alist.Free;
end;
end;