Author: William Gerbert
Parsing Strings using TParser
Answer:
Delphi has a cool class called TParser that the IDE uses to parse the source code.
You can also use it to parse strings.
This function takes a string argument and splits it into separate words for you.
1 procedure ParseThis(MyStr: string);
2 var3 MyParser: TParser;
4 MS: TMemoryStream;
5 begin6 MS := TMemoryStream.Create;
7 MS.Position := 0;
8 MS.write(MyStr[1], Length(MyStr));
9 MS.Position := 0;
10 MyParser := TParser.Create(MS);
11 MyStr := MyParser.TokenString;
12 ShowMessage(MyStr);
13 while MyParser.Token <> toEOF do14 begin15 MyParser.NextToken;
16 if MyParser.TokenSymbolIs(MyParser.TokenString) then17 begin18 MyStr := MyParser.TokenString;
19 ShowMessage(MyStr);
20 end;
21 end;
22 MyParser.Free;
23 MS.Free;
24 end;
25 26 procedure TForm1.Button1Click(Sender: TObject);
27 begin28 ParseThis('Now is the time for all men to come to the aid of their country.');
29 end;