我个人会选择不在这里使用 Pascal IO。如果您希望您的代码能够读取 Unicode 数据,那么 Pascal IO 无法帮助您。
您可以使用字符串列表执行您描述的操作来加载文件,然后SplitString
从StrUtils
单元中解析字符串。
procedure PopulateStringGrid(Grid: TStringGrid; const FileName: string);
var
Strings: TStringList;
Row, Col: Integer;
Items: TStringDynArray;
begin
Grid.RowCount := 0;//clear any previous data
Strings := TStringList.Create;
try
Strings.LoadFromFile(FileName);
Grid.RowCount := Strings.Count;
for Row := 0 to Strings.Count-1 do
begin
Items := SplitString(Strings[Row], ' ');
for Col := 0 to Grid.ColCount-1 do
if Col<Length(Items) then
Grid.Cells[Col, Row] := Items[Col]
else
Grid.Cells[Col, Row] := '0';
end;
finally
Strings.Free;
end;
end;
请注意,这SplitString
可能不是您所需要的。例如,它不会将重复的分隔符合并为一个。要了解我的意思,请考虑以下输入:
Hello World
两个单词之间有 4 个空格,SplitString
将返回以下数组:
'Hello'
''
''
''
'World'
如果您希望将连续分隔符视为一个分隔符,则可以使用DelimitedText
字符串列表的属性:
procedure PopulateStringGrid(Grid: TStringGrid; const FileName: string);
var
TextFile, Line: TStringList;
Row: Integer;
begin
Grid.RowCount := 0;//clear any previous data
TextFile := TStringList.Create;
try
Line := TStringList.Create;
try
Line.Delimiter := ' ';
TextFile.LoadFromFile(FileName);
Grid.RowCount := TextFile.Count;
for Row := 0 to TextFile.Count-1 do
begin
Line.DelimitedText := TextFile[Row];
for Col := 0 to Grid.ColCount-1 do
if Col<Line.Count then
Grid.Cells[Col, Row] := Line[Col]
else
Grid.Cells[Col, Row] := '0';
end;
finally
Line.Free;
end;
finally
TextFile.Free;
end;
end;