博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

Delphi里实现类似于C++ strtok 的函数

Posted on 2008-09-04 20:26  lake.cn  阅读(430)  评论(0)    收藏  举报

原地址: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 : stringconst 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): stringoverload;
begin
    Result :
= copy(sData, nStart, nLength);
end;

//Function To Get Characters From The String
function StrMid(const sData: string; nStart: integer): stringoverload;
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.