Original address: http://www.delphi3000.com/articles/article_4028.asp? SK =
A partof function is added here to make the behavior the same as that of strtok.
Unit Unit1;
Interface
Function Strtok (s: String ; Tok: String = '' ): String ;
VaR
Toks: String ;
Implementation
Function Partof ( Const Sdata: String ; Const Tok: String ): Boolean;
VaR
I: integer;
Begin
For I: = 1 To Length (sdata) Do
Begin
If Sdata [I] = Tok Then
Begin
Result: = True;
Exit;
End ;
End ;
Result: = False;
End ;
// 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 );
Lentok: = 1 ;
For I: = 0 To Length (toks) - Lentok Do
Begin
If Partof (Tok, strmid (toks, I, lentok )) 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 ('', ';' #10); // split with space, semicolon, break;
Secondword: = strtok ('', ';' #10); // split with space, semicolon, break;
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!
}
End .