本文主要是介绍《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
这篇关于《c和指针》笔记--strsep淘汰strtok的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!