C strtok <string.h>(备忘)

strtok

 

char   *strtok(char *str, const char *sep); 

 

Example:

 


char *token;
char *path = getenv("PATH");
/* PATH is something like "/usr/bin:/bin/usr/sbin:/sbin" */

char *copy = (char *)malloc(strlen(path) + 1);
if (copy == NULL) {
    
/* handle error */
}
strcpy(copy, path);
token 
= strtok(copy, ":");
puts(token);

while (token = strtok(0":")) {
    puts(token);
}

free(copy);
copy 
= NULL;

printf(
"PATH: %s", path);
/* PATH is still "/usr/bin:/bin/usr/sbin:/sbin" */

 

 备注

 strtok() 会修改传递给它的第一个参数的内容,因此这个字符串在调用以后将是不安全的,无法按照原先的方式使用。如果需要保留原先的字符串,可以把它复制到一个缓冲区,并把这个缓冲区的地址传递给 strtok(),而不是传递原字符串。

 

posted @ 2010-12-22 10:59  Old  阅读(498)  评论(0编辑  收藏  举报