分隔符字符串处理(strtok与strsep区别)

1、strtok原型与应用

原型:char *strtok(char *src, const char *delim);

功能:将src(原字符串)根据delim(分隔符串)分解为不同子串(连续算一个)

返回:属于当前分割的子串,当前没有分割的子串时返回NULL

#include <stdio.h>  
#include <string.h>  
  
int main(void) {  
    char s[] = "hello, world! welcome to china!";  
    char delim[] = " ,!";  
  
    char *token;  
    for(token = strtok(s, delim); token != NULL; token = strtok(NULL, delim)) {  
        printf(token);  
        printf("+");  
    }  
    printf("\n");  
    return 0;  
}  
输出:hello+word+welcome+to+china+

2、strsep原型与应用

原型:char *strsep(char * src; const char *delim);

功能:将src(原字符串)根据delim(分隔符串)分解为不同的子串(分隔符串一对一替换)

返回:属于当前分割的子串,当前没有分割的子串时返回NULL

#include <stdio.h>  
#include <string.h>  
  
int main(void) {  
    char source[] = "hello, world! welcome to china!";  
    char delim[] = " ,!";  
  
    char *s = strdup(source);  
    char *token;  
    for(token = strsep(&s, delim); token != NULL; token = strsep(&s, delim)) {  
        printf(token);  
        printf("+");  
    }  
    printf("\n");  
    return 0;  
}  
输出:hello++word++welcome+to+china+;
注:主要区别在分隔符串如果是多个字符组成且在原字符串中是连续出现的话(例delim, 原字符串中有连续的", ","! "),strtok一次统一替换为一个'\0',而strsep会挨个替换,且几个分割字符连续的话他会挨个返回空字符串,如“”,因此如果需要使用strsep的话必须要做返回值为空串的判断。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值