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