admin管理员组

文章数量:1642466

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.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


本文标签: 指针笔记strtokstrsep