Mega Code Archive

 
Categories / Delphi / Strings
 

Parsing strings

Title: Parsing strings Question: How can I extract the tokens (parse) from a given string? Answer: { With this code you can extract tokens from a string. I've provided sets for Comma Seperated fields (CS_CSV), Tab (CS_Tab) and ofcource for spaces (CS_SPACE). Warning: This code does not support "quoted strings" tokens. } Type CharSet = set of char; const CS_Space : CharSet = [' ']; const CS_CSV : CharSet = [',', ' ']; const CS_STab : CharSet = [#9, ' ']; function GetToken(var InTxt : String; SpaceChar : CharSet) : String; var i : Integer; begin { Find first SpaceCharacter } i:=1; While (i { Get text upto that spacechar } Result := Copy(InTxt,1,i-1); { Remove fetched part from InTxt } Delete(InTxt,1,i); { Delete SpaceChars in front of InTxt } i:=1; While (i Delete(InTxt,1,i-1); end; {--------------------} { Usage example: } var s : String; begin s:='Money, 600, Box, Walk_On_Moon'; Memo1.Lines.Add('"'+GetToken(s, CS_CSV) +'"'); Memo1.Lines.Add('"'+GetToken(s, CS_CSV) +'"'); Memo1.Lines.Add('"'+GetToken(s, CS_CSV) +'"'); Memo1.Lines.Add('"'+GetToken(s, CS_CSV) +'"'); end;