#include <iostream>
#include <string.h>
using namespace std;
int strStr(string haystack, string needle)
{
int n = haystack.size(), m = needle.size();//记录字符串和子串的长度
for (int i = 0; i + m <= n; i++) //从子串开始位置到结束位置最多到字符串的结束位置
{
bool flag = true;
for (int j = 0; j < m; j++) //遍历子串
{
if (haystack[i + j] != needle[j]) //如果字符串的当前位置字符与子串当前字符不等
{
flag = false;//标记为假,跳出循环
break;
}
}
if (flag) //如果找到字串,则返回子串在字符串中出现的首字符下标
{
return i;
}
}
return -1;
}
int main()
{
char p1[] = "abcdefabcdef";
char p2[] = "def";
int ret = strStr(p1, p2);
if (ret == NULL)
{
cout << "子串不存在" << endl;
}
else
{
cout << ret << endl;
}
return 0;
}