【C语言】模拟实现strstr函数
2016-07-23 16:20
363 查看
问题描述:写一个函数模拟实现strstr函数。
思路:strstr函数的功能是判断在一个字符串在另一个字符串中是否有包含,比如strstr(str,string)就是判断字符串string是否是str的子串。如果是,则该函数返回string在str中首次出现的地址;否则,返回NULL。
基于这个特点,我们可以想到将string与str进行遍历,如果对比找到,返回出现的首地址;如果找不到,返回NULL。
结果:lazy found at position 36
思路:strstr函数的功能是判断在一个字符串在另一个字符串中是否有包含,比如strstr(str,string)就是判断字符串string是否是str的子串。如果是,则该函数返回string在str中首次出现的地址;否则,返回NULL。
基于这个特点,我们可以想到将string与str进行遍历,如果对比找到,返回出现的首地址;如果找不到,返回NULL。
#include<stdio.h> #include<asset.h> char *my_strstr(const char *str, char *string) { int i=0; assert(str&&string); while('\0'!=str) { while(1) { if(string[i]!=str[i]) //从第一个字符开始匹配字符是否相同 break; if(string[i]=='\0') //判断string的字符是否遍历完成 return str; i++; } string++; } return NULL; } int main() { char string[] = "lazy"; char str[] = "The quick brown dog jumps over the lazy fox"; char *p=my_strstr(str,string); int result=p-str+1; if(p!=NULL) printf("%s found at position %d\n\n", string,result); else printf( "%s not found\n", string); system("pause"); return 0; }
结果:lazy found at position 36
相关文章推荐
- C++ const函数返回值必须为const引用
- leetcode_c++:栈:Flatten Nested List Iterator(341)
- C++ Primer 笔记(2)第二章 变量与基本类型
- leetcode_c++:栈: Verify Preorder Serialization of a Binary Tree(331 )
- 1092. To Buy or Not to Buy (20)
- leetcode_c++:栈:Remove Duplicate Letters(316 )
- vector::clear ,vector::crbegin (c++11),vector::crend(c++11)
- vector::cend (c++ 11)
- vector::cbegin (c++11)
- 大话设计模式12----外观模式
- C++ vector用法
- 并查集C++实现
- leetcode_c++:栈: Implement Queue using Stacks(232)
- c++ 在windwos上创建盘符,并且,监控盘符里面任一文件的变动事件
- 谈谈8年C++面向对象设计的经验体会
- C/C++头文件大全
- leetcode_c++:栈: Implement Stack using Queues(225)
- 模拟实现strstr函数
- Google C++编程规范--《空格的使用》
- leetcode_c++:栈: Basic Calculator(224)