Mega Code Archive

 
Categories / Delphi / Strings
 

A String Tokenizer Similar To strtok() in C++

Title: A String Tokenizer Similar To strtok() in C++ Question: The following procedure acts similar to strtok in C++. Call it once with your string (S), and then everytime you call it from there on out, you can break your string apart with tokens! Included is a function StrMid() and an overload for StrMid that simulate the Mid() function in Visual Basic. Answer: //Declare private string for the unit implementation var TokS: string //Function To Get Characters From The String function StrMid(const sData: string; nStart: integer; nLength: integer): string; overload; begin Result := copy(sData, nStart, nLength); end; //Function To Get Characters From The String function StrMid(const sData: string; nStart: integer): string; overload; begin Result := copy(sData, nStart, Length(sData) - (nStart - 1)); end; //String Tokenizer function function StrTok(S: string; Tok: string = ''): string; var i, LenTok: integer; begin if not(S = '') then begin //New String TokS := S; result := ''; Exit; end; if Tok = '' then begin //If No Token result := TokS; Exit; end; LenTok := Length(Tok); for i := 0 to Length(TokS) - LenTok do begin if StrMid(TokS, i, LenTok) = Tok then begin //If Token Found result := StrMid(TokS, 1, i - LenTok); TokS := StrMid(TokS, i + LenTok + 1); Exit; end; end; //If Program Reaches Here, Return The Rest Of The String result := TokS; TokS := ''; end; Therefore, for example, if you defined a string: var S: string and set S to 'Hello World' S := 'Hello World'; and then call StrTok() like so: StrTok(S); The procedure will store the string, from now on, calling StrTok() with no S value and a token (such as a space ' '), the program will return everything in the string up to the token. EX: var firstWord, secondWord: string begin StrTok(S); firstWord := StrTok('', ' '); secondWord := StrTok('', ' '); end; //Doing this will break apart the string S at the token (' ') into the first word and the second word. Good luck!