2010. szeptember 3., péntek

Parsing Strings using TParser


Problem/Question/Abstract:

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.

procedure ParseThis(MyStr: string);
var
  MyParser: TParser;
  MS: TMemoryStream;
begin
  MS := TMemoryStream.Create;
  MS.Position := 0;
  MS.Write(MyStr[1], Length(MyStr));
  MS.Position := 0;
  MyParser := TParser.Create(MS);
  MyStr := MyParser.TokenString;
  ShowMessage(MyStr);
  while MyParser.Token <> toEOF do
  begin
    MyParser.NextToken;
    if MyParser.TokenSymbolIs(MyParser.TokenString) then
    begin
      MyStr := MyParser.TokenString;
      ShowMessage(MyStr);
    end;
  end;
  MyParser.Free;
  MS.Free;
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  ParseThis('Now is the time for all men to come to the aid of their country.');
end;

Nincsenek megjegyzések:

Megjegyzés küldése