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

1、strtok原型与应用

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

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

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

  1. #include <stdio.h>
  2. #include <string.h>
  3. int main(void) {
  4. char s[] = "hello, world! welcome to china!";
  5. char delim[] = " ,!";
  6. char *token;
  7. for(token = strtok(s, delim); token != NULL; token = strtok( NULL, delim)) {
  8. printf(token);
  9. printf( "+");
  10. }
  11. printf( "\n");
  12. return 0;
  13. }
输出:hello+word+welcome+to+china+

2、strsep原型与应用

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

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

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

  1. #include <stdio.h>
  2. #include <string.h>
  3. int main(void) {
  4. char source[] = "hello, world! welcome to china!";
  5. char delim[] = " ,!";
  6. char *s = strdup(source);
  7. char *token;
  8. for(token = strsep(&s, delim); token != NULL; token = strsep(&s, delim)) {
  9. printf(token);
  10. printf("+");
  11. }
  12. printf("\n");
  13. return 0;
  14. }
输出:hello++word++welcome+to+china+;
注:主要区别在分隔符串如果是多个字符组成且在原字符串中是连续出现的话(例delim, 原字符串中有连续的", ","! "),strtok一次统一替换为一个'\0',而strsep会挨个替换,且几个分割字符连续的话他会挨个返回空字符串,如“”,因此如果需要使用strsep的话必须要做返回值为空串的判断。
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值