Chinaunix首页 | 论坛 | 博客
  • 博客访问: 238436
  • 博文数量: 62
  • 博客积分: 973
  • 博客等级: 准尉
  • 技术积分: 530
  • 用 户 组: 普通用户
  • 注册时间: 2011-11-16 23:25
文章分类

全部博文(62)

文章存档

2013年(1)

2012年(14)

2011年(47)

分类: C/C++

2011-11-27 23:23:42

查了半天终于找到一个跟我思路相符的:
http://blog.sina.com.cn/s/blog_628821950100ynbu.html
 
  1. char* my_strstr(char *str,char *sub)
  2. {
  3.     char *pstr,*psub,*ptmp;
  4.     if(NULL == str || NULL == sub)
  5.         return (char *)0;
  6.     for(ptmp=str; *ptmp; ptmp++)
  7.     {
  8.         psub=sub;
  9.         pstr=ptmp;
  10.         while(*psub==*pstr && *psub!='\0')
  11.         {
  12.             psub++;
  13.             pstr++;
  14.         }
  15.         if(*psub=='\0')
  16.             return ptmp;
  17.     }
  18.     return NULL;
  19. }
系统函数strstr()是这道题的灵感来源。
  1. #include <stdio.h>

  2. char* delsubstr(char *str, char *sub)
  3. {
  4.     char *ptmp,*pstr,*psub;    
  5.     char *pdst;

  6.     if(NULL == str || NULL == sub)
  7.         return (char *)0;
  8.     pdst = str;
  9.     pstr = str;
  10.     while(*pstr)
  11.     {
  12.         ptmp = pstr;
  13.         psub = sub;
  14.         while( (*psub == *ptmp) && *ptmp )
  15.         {
  16.             psub++;
  17.             ptmp++;
  18.         }
  19.         if('\0' == *psub)
  20.         {
  21.             pstr = ptmp;
  22.         }
  23.         else
  24.         {
  25.         // VC下会报错“写入0x...时发生访问冲突”
  26.             *pdst++ = *pstr++;
  27.         }
  28.     }
  29.     *pdst = '\0';

  30.     return str;
  31. }


  32. void main()
  33. {
  34.     char str[40],sub[20];
  35.     printf("Please input a string:\n");
  36.     scanf("%s",str);
  37.     printf("Please input the sub string:\n");
  38.     scanf("%s",sub);

  39.     printf("output string: %s\n", delsubstr(str, sub) );
  40. }
 
阅读(1852) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~