Mega Code Archive

 
Categories / Delphi / Functions
 

GetToken function II Modified from Sebastian Volland work

Title: GetToken function II - Modified from Sebastian Volland work Question: A GetToken function modified. It will get the next token on a string delimited by special characters, it will also alter the initial string so you can call this function several times to get "theNextToken" much like strtok() does in C. Answer: { (C) MMI, Luis F. Franco, Based on Sebastian Volland article at Delphi3000 ( http://www.delphi3000.com ) http://www.delphi3000.com/article.asp?ID=1149 Syntax ------ GetToken(srcString,delStr,nTok); srcString : String - String to be parsed delStr : String - String containing a "list" of possible delimiters numTok : Byte - Get me token number nTok, by default this one is 1 (I normally want just the first token) Example: -------- a := "AA,BB/CC,DD"; // You can have two separators, the /s and the ,s if you don't care about // them and just want the "next" token, you can use: theResult := getToken(a,',/'); // Since a is being passed as reference, the value of a its reduced, this // makes simplier to make succesive calls to the function, this is what // (just like C's strtok() does) // I was working at: // This came from somewhere else: It is financial data: // date, open price, open value, high value, low value, close, volume a := '01-Jan-00,3.25,3.75,3,3,19283'; // So, I parse it with: date := getToken(a,','); open := getToken(a,','); high := getToken(a,','); low := getToken(a,','); close := getToken(a,','); volume := getToken(a,','); Note: If it doesn't find the desired delimitator, it will return "a", this is intentional, since a line on CSV files NEVER ends on a ',', in this case variable a won't be modified either. } function GetToken(var a: String; Sep: String; Num: Byte = 1) : string; var Token : String; StrLen : Integer; TNum : Integer; TEnd : Integer; i : integer; f : boolean; begin strLen := Length(a); TNum := 0; TEnd := StrLen; while ((TNum 0)) do begin f := false; for i := 1 to length(sep) do begin TEnd := pos(copy(sep,i,1),a); if TEnd 0 then begin StrLen := min(TEnd, strLen); f := true; end; end; if f then TEnd := StrLen; if TEnd0 then begin Token := Copy(a,1,TEnd-1); Delete(a,1,TEnd); Inc(TNum); end else Token:=a; end; Result := token; end;