描述
给定字符串s和t,判断t在s中是否存在,如果存在,返回首次出现的位置(即首次出现的子串首字符的位置,从0开始计算)。
其中s称为主串,t称为模式串。
部分代码已经完成,您只需完成strstr函数的编写,请勿包含给定代码。
int strstr(char* s, char* t);//s为主串,t为模式串
输入
第一行为字符串s;
第二行为字符串t。
s和t均不含空格。字符串长度均不超过100。
输出
如果存在输出首次出现的位置(从0开始)。
否则输出-1。
样例输入
ababc
abc
样例输出
2
基于Monster 组和GPT的调写:
#include <stdio.h>
#include <string.h>
int strstr(char* s, char* t)
{
int n = strlen(s);
int m = strlen(t);
for (int i = 0; i <= n - m; i++) {
int j;
for (j = 0; j < m; j++) {
if (s[i + j] != t[j]) break;
}
if (j == m) return i;
}
return -1;
}
int main()
{
char s[101], t[101];
scanf("%s", s);
scanf("%s", t);
int pos = strstr(s, t);
printf("%d\n", pos);
return 0;
}
头文件只有#include <stdio.h>
供参考:
#include <stdio.h>
int strstr(char* s, char* t)
{
int i = 0, j = 0, pos = 0;
while (s[i] && t[j])
{
if (s[i] == t[j]){
pos = i;
while (s[pos] == t[j] && t[j] && s[pos]) pos++, j++;
if (t[j]) i++, j = 0;
}
else
i++ ,j = 0;
}
if (!t[j])
return i;
else
return -1;
}
int main()
{
char s[101], t[101];
scanf("%s", s);
scanf("%s", t);
int pos = strstr(s, t);
printf("%d", pos);
return 0;
}
不知道你这个问题是否已经解决, 如果还没有解决的话: