C语言中利用strstr函数进行字符串分割

By Minidxer | February 3, 2008

在前面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. }

Topics: 程序开发相关 | 7 Comments » | Tags: , , , ,

你可能还对下列文章感兴趣:

7 comments | Add One

  1. sunyu - 09/23/2008 at 12:24 pm

    错误的

  2. teloon - 03/26/2009 at 8:38 pm

    gcc编译不通过,段错误~

  3. Minidxer - 03/27/2009 at 8:35 am

    什么错误信息?

  4. tw - 07/18/2009 at 4:27 pm

    char *haystack=”aaa||a||bbb||c||ee||”;
    haystack是字符串常量
    buf[0]=”;
    试图修改字符串常量,会有问题。

  5. 陈成 - 08/7/2009 at 4:38 pm

    删除 buf[0]=”;

  6. 示例错误 - 03/5/2010 at 1:52 pm

    #include
    #include

    int main(int argc,char **argv)
    {
    char temp[10];
    char *haystack=”aaa||a||bbb||c||ee||”;
    char *needle=”||”;
    char* buf = strstr( haystack, needle);
    while( buf != NULL )
    {
    // buf[0]=”; 替换为
    strncpy(temp, haystack, buf-haystack);
    temp[buf-haystack] =0;
    printf( “%s\n “, temp); //haystack);

    haystack = buf + strlen(needle);
    /* Get next token: */
    buf = strstr( haystack, needle);
    }
    return 0;
    }

  7. 示例错误 - 03/5/2010 at 1:54 pm

    原因分析:
    char *haystack=”aaa||a||bbb||c||ee||”;
    定义,”aaa||a||bbb||c||ee||”为静态存储区的常量值,此值不能被修改。
    如果此值在变量区,则程序正确。

Leave a Comment

Name(*):

E-Mail(*) :

Website :

Comments :

Search Posts