Delphi - Parsing Strings
I have written my own library to manipulate strings - included is a parse function.
This is not efficient code, but it works.
Code
function Mid_mc(s:string; StartPos: integer; EndPos: integer = -1):string;
// NumOfCharacters = -1 means "to the end of the string"
var
i, j: integer;
begin
i := StartPos;
if (i < 1) then i := 1;
if (i > length(s)) then begin
Mid_mc := '';
exit;
end;
if EndPos < 0 then
j := length(s)
else
j := EndPos;
Mid_mc := copy(s, i, j-i+1);
end; // Mid_mc integer, integer
function InStr_mc(S, Pattern: string; Start: integer=1;
CaseSensitive:boolean=false):integer;
var
tempStr: string;
i, j: integer;
begin
i := Start;
if (i < 1) then i := 1;
if (i > length(s)) then begin
InStr_mc := 0;
exit;
end;
tempStr := copy(s, i, length(s));
if CaseSensitive then
j := pos(Pattern, tempStr)
else
j := pos(upperCase(Pattern), upperCase(tempStr));
if J<>0 then j := i+j-1 ;
InStr_mc := j;
end; // InStr_mc
// Accepts a string and returns a stringList
function ParseString_mc(s: string; delimiters: string = WhiteSpace_mc)
: TStringList;
var
tempStr, token: string;
list: TStringList;
i,j: integer;
begin
tempStr := s;
list:= TStringList.Create;
i:=1;
if length(s)>0 then repeat
while InStr_mc(delimiters, tempStr[i]) <> 0 do begin
i := i+1;
if i > length(s) then break;
end;
j:= i;
if j <= length(s) then
while InStr_mc(delimiters, tempStr[j]) = 0 do begin
j := j+1;
if j > length(s) then break;
end;
if i <= length(s) then begin
token:=mid_mc(tempStr, i, j-1);
list.Append(token);
end;
i := j+1;
until i >= length(s) ;
ParseString_mc := list;
end; // ParseString_mc
Alternatives
You could also use
Delphi's TParser class.
Author: Robert Clemenzi -
clemenzi@cpcug.org