Feb 03
在前面C语言中利用strtok函数进行字符串分割介绍的strtok函数,比较适合多个字符(也就是字符串)作分隔符的场合,而很多时候我们仅仅需要某一个特定的字符来分割字符串,当然利用strtok也可以实现,不过这里介绍的strstr效率上来说更加适合。
原型:extern char *strstr(char *haystack, char *needle);
所在头文件:#include <string.h>
功能:从字符串haystack中寻找needle第一次出现的位置(不比较结束符NULL)。
说明:返回指向第一次出现needle位置的指针,如果没找到则返回NULL。
具体使用例子:
Download: strstr_sample.c
- #include <stdio.h>
- #include <string.h>
- int main(int argc,char **argv)
- {
- char *haystack="aaa||a||bbb||c||ee||";
- char *needle="||";
- char* buf = strstr( haystack, needle);
- while( buf != NULL )
- {
- buf[0]='\0';
- printf( "%s\n ", haystack);
- haystack = buf + strlen(needle);
- /* Get next token: */
- buf = strstr( haystack, needle);
- }
- return 0;
- }
