其他分享
首页 > 其他分享> > 分割字符 strtok_r

分割字符 strtok_r

作者:互联网

函数原型

#include <string.h>

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

char *strtok_r(char *str, const char *delim, char **saveptr);

例子

#include <stdio.h>
#include <string.h>
int main(int argc, char **argv)
{
    char *saveptr;
    char *s;
    
    char arr[50] = "hello,world,color";
    char *buf = arr;
    //char *buf = "hello,world,color"; /* crash coredump */
    char *dem = ",";
    while((s = strtok_r(buf, dem, &saveptr)) != NULL){
        if ( s != NULL && saveptr != NULL){
            printf("s=%s saveptr=%s\n", s, saveptr);
            buf = NULL;
        }
    }
    return 0;
}

注意这里buf不能直接是char *buf = "hello,world,color",会crash的

# ./a.out 
s=hello saveptr=world,color
s=world saveptr=color
s=color saveptr=

标签:字符,分割,strtok,color,saveptr,char,world,NULL,buf
来源: https://www.cnblogs.com/tangshunhui/p/16639235.html