描述
Implement strStr().
Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.
Implement strStr().
Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.
#include<iostream>
#include<string>
#include<vector>
using namespace std;
int ImplementStr(string mainstr, string substr)
{
int mainlegth = mainstr.size();
int sublength =substr.size();
for (int i = 0; i < mainlegth;i++)
{
int k = i;
int j;
for (j = 0; j < sublength;j++)
{
if (mainstr[k] == substr[j]&&k<mainlegth)
{
k++;
}
else
break;
}
if (j == sublength)
return i;
}
return -1;
}
int main()
{
string mainstr = "I LOVE SEU UNIVERSITY IN NANJING china!";
string substr = "china!";
int index = ImplementStr(mainstr, substr);
cout << index << endl;
}