算法分析
strtok是用来分隔字符串,首次使用strtok时,str指向待分隔的字符串;后续调用要将str置为NULL,直至返回值为NULL。
因此,需要一个static变量指向str变量。
c++代码
//str:待分隔的源字符串
//delimeter:分隔符
char* strtok(char* str, const char* delimeter)
{
//静态变量,指向带分隔的源字符串
static char* staticStr = NULL;
//指向分隔符的指针
const char* pDelimeter = NULL;
//返回值
char* pRetStr = NULL;
//标志位
bool bFind = false;
if(str != NULL)
{
staticStr = str;
}
if(*staticStr == '\0')
{
return NULL;
}
pRetStr = staticStr;
while(*staticStr != '\0')
{
for(pDelimeter = delimeter; *pDelimeter != '\0';pDelimeter++ )
{
if(*pRetStr == *pDelimeter)
{
pRetStr++;
break;
}
if(*staticStr == *pDelimeter)
{
bFind = true;
*staticStr = '\0';
}
}
staticStr++;
if(bFind)
{
break;
}
}
return pRetStr;
}
测试代码
int _tmain(int argc, _TCHAR* argv[])
{
char data[20] = "salfgdfogffhe";
char* result = strtok(data,"gd");
cout<<result<<endl;
while(result != NULL)
{
result = strtok(NULL,"gd");
if(result != NULL)
{
cout<<result<<endl;
}
}
return 0;
}