分割字符 strtok_r

函数原型

#include <string.h>

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

char *strtok_r(char *str, const char *delim, char **saveptr);
  • str: 要分割的字符

  • delim: 分隔符

  • saveptr: str分割后的后部分

  • 返回值: str分割后的后部分,如果没有满足的条件的则返回NULL

例子

#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=
posted @ 2022-08-30 14:54  梦过无声  阅读(116)  评论(0编辑  收藏  举报