调用方式:char *strtok(char *str1,char *str2);
功能说明:函数strtok()返回字符串str1中指向一个由str2所指定的字符或者字符串的分隔符的指针,当没有要返回的分隔符时,就返回一个空指针。
函数strtok()实际上修改了有str1指向的字符串。每次找到一个分隔符后,一个空(NULL)就被放到分隔符处,函数用这种方法来连续查找该字符串。
例子1:
#include <string.h>
#include <stdio.h>
int main( int argc, char *argv[] )
{
char *p;
char str[100]="This is a test,and you can use it";
p = strtok(str," "); // 注意,此时得到的 p为指向字符串:"This",即在第一个分隔符前面的字符串,即每次找到一个分隔符后,一个空(NULL)就被放到分隔符处,所以此时NULL指针指向后面的字符串:"is a test ,and you can use it"。
printf("%s/n",p); //此时显示:This
do
{
p = strtok(NULL, ","); //NULL即为上面返回的指针,即字符串:"is a test ,and you can use it"。
if(p)
printf("%s/n",p);
}while(p);
return 1;
}
例子2:
#include <string.h>
#include <stdio.h>
char string[] = "A string/tof ,,tokens/nand some more tokens";
char seps[] = " ,/t/n";
char *token;
void main( void )
{
printf( "%s/n/nTokens:/n", string );
/* Establish string and get the first token: */
token = strtok( string, seps );
while( token != NULL )
{
/* While there are tokens in "string" */
printf( " %s/n", token );
/* Get next token: */
token = strtok( NULL, seps );
}
}
例子2 Output
A string of ,,tokens
and some more tokens
Tokens:
A
string
of
tokens
and
some
more
tokens
例子3:
CString strTest = "123 45";
//some other code
CString strTest2 = strTest;
char seps[] = " ";
char* pToken = 0;
//char* pStr = strTest2.GetBuffer(0);
pToken = strtok((char*)(LPCTSTR)strTest2, seps);
//pToken = strtok(pStr, seps);
while(pToken)
pToken = strtok(NULL, seps);
//strTest2.ReleaseBuffer(0);
说明:
运行上面的代码,可以看到strTest的值也变了,呵呵,这就是程序中一些关与CString的奇怪问题的起源.如果用注释中的GetBuffer/ReleaseBuffer方法,就一点问题也没有了.
同样,对于ReleaseBuffer的参数,缺省的是-1,但是我不建议.因为-1表示使用当前的00结束符位置来确定新的长度.而上面的例子中,strtok是会重新设置00结束符的,所以,安全的做法,就是把这个CString的长度设为0,ReleaseBuffer(0),反正它的内容已经变了,也没有人要用了.
说明一下,GetBuffer/ReleaseBuffer方法只能保证strTest不变,strTest2还是会变的.所以,对于一个成员变量,比如m_strTest2调用ReleaseBuffer要多一个心眼,局部变量就不用想这么多了.
那么怎么从最开始就意识到程序写错了呢?上面代码中(char*)(LPCTSTR)是很危险的,把const去掉了,否则strtok是编译不过的,也从一个侧面说明了const的重要性.
例子4:
CString str( "123 45" );
CString resToken;
int curPos= 0;
while (curPos != -1)
{
resToken= str.Tokenize(" ", curPos);
cout << (LPCTSTR)resToken << endl;
};
说明:
VC6的CString是没有Tokenize这个函数的,VC7的MFC中的CString才有。
7412



被折叠的 条评论
为什么被折叠?



