实例要求:
- 1、请你实现
C库函数strstr()(stdio.h & string.h),请在haystack 字符串中找出 needle 字符串的第一个匹配项的下标(下标从 0 开始); - 2、函数声明:
int strStr(char* haystack, char* needle); - 参数:
- 1、haystack -->
被检索的字符串; - 2、needle --> haystack字符串内要
匹配的子字符串; - 返回值:
- 1、
函数strStr()返回在 haystack中第一次出现 needle 字符串的位置; - 2、在 haystack中未找到则
返回-1;
案例展示:

实例分析:
- 1、利用
strlen函数分别求出字符串haystack和needle的长度; - 2、
双重for嵌套循环遍历两个字符串; - 3、设置
标志位flag,初值为0; - 4、当
flag等于0时,返回第一个匹配项的下标; - 5、其他的情况则
返回-1;
示例代码:
int strStr(char* haystack, char* needle) {int len1 = strlen(haystack);int len2 = strlen(needle);int i = 0;int j = 0;int flag = 0;for(i = 0; i < len1; i++){flag = 0;for(j = 0; j < len2; j++){if(haystack[i+j] != needle[j]){flag = 1;break;}}if(flag == 0){return i;}}return -1;}
运行结果:

