嵌入式 字符串分割(切分):strtok()与strsep()

strtok()与strsep()都能够实现字符串的切分,但两个函数的使用方法略有不同。

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#include <unistd.h>

int main()
{
    char * pp;
    char *cc = pp = (char *) malloc (sizeof(char)* 15);
    strcpy(cc,"cc;dd;3;4;5;");
    
    while(strcmp(pp,"")!=0)
    {
        printf("strsep: %s\n",strsep(&pp, ";")); //每次调用都会改变pp的指针地址
    }
    printf("cc:%x pp:%x\n",cc,pp); //此处可以看出cc的地址与pp的地址已经不同了
    
    strcpy(cc,"cc;dd;3;4;5;");    //重新初始化cc的内容,使用strok()进行字符串分割
    char *s = strtok(cc,";");
    printf("strtok:%s\n",s);
    while((s=strtok(NULL,";"))!=NULL)
        printf("strtok:%s\n",s);
    
    printf("cc:%s\n",cc);
    free(cc);
    return 0;
}

上面可以看出strsep()与strtok()的实现方法是有所不同的,使用过程中需要注意。
程序运行结果如下

嵌入式 字符串分割(切分):strtok()与strsep()_第1张图片


你可能感兴趣的:(嵌入式 字符串分割(切分):strtok()与strsep())