Mirror

Parsing strings (Views: 100)


Problem/Question/Abstract:

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 <= length(InTxt)) and not (InTxt[i] in SpaceChar) do
    inc(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 <= length(InTxt)) and (InTxt[i] in SpaceChar) do
    inc(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;

<< Back to main page