article

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

Email
Submitted on: 1/1/2015 1:48:00 PM
By: Ty (from psc cd)  
Level: Beginner
User Rating: By 13 Users
Compatibility: Delphi 5, Delphi 4, Pre Delphi 4
Views: 3430
 
     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.

 
				//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 and use this code well!


Other 1 submission(s) by this author

 


Report Bad Submission
Use this form to tell us if this entry should be deleted (i.e contains no code, is a virus, etc.).
This submission should be removed because:

Your Vote

What do you think of this article (in the Beginner category)?
(The article with your highest vote will win this month's coding contest!)
Excellent  Good  Average  Below Average  Poor (See voting log ...)
 

Other User Comments


 There are no comments on this submission.
 

Add Your Feedback
Your feedback will be posted below and an email sent to the author. Please remember that the author was kind enough to share this with you, so any criticisms must be stated politely, or they will be deleted. (For feedback not related to this particular article, please click here instead.)
 

To post feedback, first please login.