原型:extern char *strtok(char *s, char *delim);
用法:#include <string.h>
功能:分解字符串为一组标记串。s为要分解的字符串,delim为分隔符字符串。
说明:首次调用时,s必须指向要分解的字符串,随后调用要把s设成NULL。
strtok在s中查找包含在delim中的字符并用NULL('/0')来替换,直到找遍整个字符串。
返回指向下一个标记串。当没有标记串时则返回空字符NULL。
举例:
#include <string.h>
#include <stdio.h>
int main(int argc, char* argv[])
...{
char s[]="Golden Global View"; // 注意与 char *s="Golden Global View" 的区别
char *d=" ";
char *p;
p=strtok(s,d);
while (p)
... {
printf("%s ",p); //printf("%s",s);
p=strtok(NULL,d); //it is strange here, the function knows the source string is *p, which is not indicated obviously
}
return 0;
}
#include <stdio.h>
int main(int argc, char* argv[])
...{
char s[]="Golden Global View"; // 注意与 char *s="Golden Global View" 的区别
char *d=" ";
char *p;
p=strtok(s,d);
while (p)
... {
printf("%s ",p); //printf("%s",s);
p=strtok(NULL,d); //it is strange here, the function knows the source string is *p, which is not indicated obviously
}
return 0;
}
output:
Golden
Global
View
如果改成
printf("%s",s),
则结果变成
Golden,Golden,Golden
如果
d
被定义成
char *d="ol"
,则输出为
G
den G
ba
View
结果看出,凡是在字符串中出现
'o'
或者
'l'
的地方都被置换成了
'/0'
,然后输出字符串。