问题
I have a text file that has, on any given row, data that are expressed both in text format and in numeric format. Something like this:
Dog 5 4 7
How do I write a file reading routine in Delphi that reads this row and assigns the read values into the correct variables ("Dog" into a string variable and "5", "4" and "7" into real or integer variables)?
回答1:
You can use SplitString from StrUtils to split the string into pieces. And then use StrToInt to convert to integer.
uses
StrUtils;
....
var
Fields: TStringDynArray;
....
Fields := SplitString(Row, ' ');
StrVar := Fields[0];
IntVar1 := StrToInt(Fields[1]);
IntVar2 := StrToInt(Fields[2]);
IntVar3 := StrToInt(Fields[3]);
And obviously substitute StrToFloat if you have floating point values.
回答2:
Take TJclStringList from Jedi Code Library.
On 1st step you take one list and do .LoadFromFile to split the file to rows. On second step you iterated through those rows and set secondary stringlist by those lines with space as delimiter. Then you iterate through secondary string list and do what u want.
- http://wiki.delphi-jedi.org/wiki/JCL_Help:IJclStringList.Split@string@string@Boolean
- Split a string into an array of strings based on a delimiter
- https://stackoverflow.com/search?q=%5Bdelphi%5D+string+split
Like that
var slF, slR: IJclStringList; ai: TList<integer>; s: string; i: integer;
action: procedure(const Name: string; Const Data: array of integer);
slF := TJclStringList.Create; slF.LoadFromFile('some.txt');
slR := TJclStringList.Create;
for s in slF do begin
slR.Split(s, ' ', true);
ai := TList<Integer>.Create;
try
for i := 1 to slR.Count - 1 do
ai.Add(StrToInt(slR[i]));
action(slR[0], ai.ToArray);
finally ai.Free; end;
end;
回答3:
You can use File of TRecord, with TRecord. For example:
type TRecord = packed record
FName : String[30];
Val1: Integer;
Val2: Integer;
Val3: Integer;
end;
And simple procedure:
procedure TMainForm.Button1Click(Sender: TObject);
var
F: file of TRecord;
Rec : TRecord;
begin
AssignFile(F, 'file.dat');
try
Reset(F);
Read(F, Rec);
finally
CloseFile(F);
end;
end;
来源:https://stackoverflow.com/questions/14454482/how-do-i-read-a-row-from-a-file-that-has-both-numbers-and-letters-in-delphi-2010