6-9 字符串匹配 - C/C++ 数组及字符串
分数 10
全屏浏览题目
切换布局
作者 海洋饼干叔叔
单位 重庆大学
函数findSubStr()用于从以0结尾的字符数组s中查找其子串s1的位置,如果找到,返回起始下标,否则返回-1。
int findSubStr(char s[], char s1[]);
举例:字符串'tri'在字符串'string'中的起始下标为1;在字符串'tom&jerry'中找不到子串'jack',函数应返回-1。
请定义上述findSubStr()函数,使得下述程序可以运行并产生正确的执行结果。
函数接口定义:
int findSubStr(char s[], char s1[]);
裁判测试程序样例:
#include <stdio.h> #include <string.h> #include <stdbool.h> //findSubStr()函数定义处 int main() { char s1[1000] = ""; char s2[1000] = ""; scanf("%s",s1); scanf("%s",s2); int r = findSubStr(s1,s2); if (r<0) printf("Not found."); else printf("Found \'%s\' at position %d of \'%s\'",s2,r,s1); return 0; }
输入样例:
tomHat
om
输出样例:
Found 'om' at position 1 of 'tomHat' int findSubStr(char s[], char s1[])
{
int i,j=0,counter=0,k;
for(i=0;i<strlen(s);i++)
{
if(s[i]==s1[j])
{ counter++;
j++;
k=i;
}
else
{ j=0;
counter=0;
}
if(strlen(s1)==counter) break;
}
if(strlen(s1)==counter) return k-strlen(s1)+1;
else return -1;
}