查了半天终于找到一个跟我思路相符的:
http://blog.sina.com.cn/s/blog_628821950100ynbu.html
- char* my_strstr(char *str,char *sub)
- {
- char *pstr,*psub,*ptmp;
- if(NULL == str || NULL == sub)
- return (char *)0;
- for(ptmp=str; *ptmp; ptmp++)
- {
- psub=sub;
- pstr=ptmp;
- while(*psub==*pstr && *psub!='\0')
- {
- psub++;
- pstr++;
- }
- if(*psub=='\0')
- return ptmp;
- }
- return NULL;
- }
系统函数strstr()是这道题的灵感来源。
- #include <stdio.h>
- char* delsubstr(char *str, char *sub)
- {
- char *ptmp,*pstr,*psub;
- char *pdst;
- if(NULL == str || NULL == sub)
- return (char *)0;
- pdst = str;
- pstr = str;
- while(*pstr)
- {
- ptmp = pstr;
- psub = sub;
- while( (*psub == *ptmp) && *ptmp )
- {
- psub++;
- ptmp++;
- }
- if('\0' == *psub)
- {
- pstr = ptmp;
- }
- else
- {
- // VC下会报错“写入0x...时发生访问冲突”
- *pdst++ = *pstr++;
- }
- }
- *pdst = '\0';
- return str;
- }
- void main()
- {
- char str[40],sub[20];
- printf("Please input a string:\n");
- scanf("%s",str);
- printf("Please input the sub string:\n");
- scanf("%s",sub);
- printf("output string: %s\n", delsubstr(str, sub) );
- }
阅读(1902) | 评论(0) | 转发(0) |