原地址:http://www.delphi3000.com/articles/article_4028.asp?SK=
這裡加上了一個PartOf函數,使行為和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.