c语言字符串分离函数 - strtok

这里我以“Knowing that there are tigers in the mountains, they prefer to travel in the mountains.”为例

以空格隔开分离:

 while ((retptr=strtok(ptr, " ")) != NULL) {
        printf("substr[%d]:%s\n", i++, retptr);
        ptr = NULL;
    }

运行结果:

c语言字符串分离函数 - strtok

以逗号隔开:

c语言字符串分离函数 - strtok

在关于一些字符串的处理上,这个函数很轻松的帮我们得到想要的分离结果。

#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[])
{
    char test_str[] = "Knowing that there are tigers in the mountains, they prefer to travel in the mountains.";
    char *ptr,*retptr;
    int i=0;
 
    ptr = test_str;
 
    while ((retptr=strtok(ptr, ",")) != NULL) {
        printf("substr[%d]:%s\n", i++, retptr);
        ptr = NULL;
    }
 
    return 0;
}