我個人會選擇不使用這裏帕斯卡IO。如果你想讓你的代碼能夠讀取Unicode數據,那麼Pascal IO無法幫助你。
您可以使用字符串列表來加載文件,然後從StrUtils
單元執行SplitString
來解析字符串。
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;
你爲什麼使用Pascal IO?爲什麼不只是將文件加載到字符串列表並使用['SplitString'](http://docwiki.embarcadero.com/VCL/en/StrUtils.SplitString)函數來分割每一行? – 2012-02-05 22:58:32
忽略** NO PASCAL I/O **幫派,對於這項任務很好。您的問題陳述不一致,如果多於一個連續的數字缺失,您將如何確定職位? – OnTheFly 2012-02-06 00:30:40
@ user539484純粹的毒液和惡意。沒有優雅。 – 2012-02-06 17:31:31