C库函数strstr()
(stdio.h & string.h
),请在 haystack 字符串中找出 needle 字符串
的第一个匹配项的下标
(下标从 0 开始
);int strStr(char* haystack, char* needle);
被检索的字符串
;匹配的子字符串
;函数strStr()
返回在 haystack中第一次出现 needle 字符串的位置
;返回-1
;strlen函数
分别求出字符串haystack和needle的长度
;双重for嵌套循环
遍历两个字符串
;标志位flag
,初值为0
;flag等于0
时,返回第一个匹配项的下标
;返回-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;
}
原文地址:https://blog.csdn.net/qq_41878292/article/details/136074993
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若转载,请注明出处:http://www.7code.cn/show_67647.html
如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱:suwngjj01@126.com进行投诉反馈,一经查实,立即删除!