《c和指针》笔记--strsep淘汰strtok

strsep和strtok是c语言中对字符串进行分割的函数,关于具体用法本篇不做详细说明。

这里只说明下2个函数的不同和相同之处。


1.strsep淘汰strtok

注:摘自Linux内核2.6.29,说明了这个函数已经不再使用,由速度更快的strsep代替。
  /*
  * linux/lib/string.c
  *
  * Copyright (C) 1991, 1992 Linus Torvalds
  */
  /*
  * stupid library routines.. The optimized versions should generally be found
  * as inline code in <asm-xx/string.h>
  *
  * These are buggy as well..
  *
  * * Fri Jun 25 1999, Ingo Oeser <ioe@informatik.tu-chemnitz.de>
  * - Added strsep() which will replace strtok() soon (because strsep() is
  * reentrant and should be faster). Use only strsep() in new code, please.
  *
  * * Sat Feb 09 2002, Jason Thomas <jason@topic.com.au>,
  * Matthew Hawkins <matt@mh.dropbear.id.au>
  * - Kissed strtok() goodbye
  */


2.strtok是不可重入的,strseq是可重入的。(还有一个strtok_r是strtok的可重入版本)

3.strsep和strtok都对修改了src字符串。

4.strsep和strtok对字符串分割结果不一致。

关于3和4,详细参见如下2个sample:

strtok:

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

int main(void)
{
char input[] = "a;a,;bc,;d";
char *p;

for(p = strtok(input, ",;");p!=NULL;p=strtok(NULL, ",;")){
        printf("%s\n", p);
}

printf("original String:%s\n",input);

return 0;
}

运行结果为:

a
a
bc
d
original String:a


strsep

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

int main(void)
{
        char input[] = "a;a,;bc,;d";
        char *string = input;
        char *p;

        while((p = strsep(&string,",;"))!=NULL)
        printf("%s\n",p);
        printf("original String:%s\n",input);
        return 0;
}

运行结果为:

a
a

bc

d
original String:a


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值