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
  1. #include <stdio.h>
  2. #include <string.h> 
  3.  
  4. int main(int argc,char **argv)
  5. {
  6. char *haystack="aaa||a||bbb||c||ee||";
  7. char *needle="||";
  8. char* buf = strstr( haystack, needle);
  9. while( buf != NULL )
  10. {
  11.     buf[0]='\0';
  12.     printf( "%s\n ", haystack);
  13.     haystack = buf + strlen(needle);
  14.     /* Get next token: */
  15.     buf = strstr( haystack, needle);
  16. }
  17.    return 0;
  18. }

written by Minidxer  |  tags: , , , ,

Related Post

Leave a Reply