個人的には、ここでは 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
正確に必要なものではない可能性があることに注意してください。たとえば、繰り返される区切り文字を 1 つに結合しません。私が何を意味するかを理解するには、次の入力を検討してください。
Hello World
2 つの単語の間には 4 つのスペースがありSplitString
、次の配列が返されます。
'Hello'
''
''
''
'World'
連続した区切り文字を 1 つの区切り文字として扱いたい場合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;