我是一名编程学生。我被要求编写一个程序来搜索另一个字符串的子字符串,但我不打算使用find()
字符串类中提供的函数。到目前为止,我编写的代码有效,但它使用了该find()
函数。如何将其更改为不使用 find 函数并仍然给我子字符串的位置?这是我的代码:
#include <iostream>
#include <string>
using namespace std;
int f_r(string, string);
int main()
{
string s;
string t;
cout << "\nEnter the string to be searched: ";
getline(cin,s);
cout << "Now enter the string you want to search for: ";
cin >> t;
if (f_r(s,t) == 0)
{
cout << "\n Substring could not be found.";
}
else
{
cout << "\nThe index of substring is = " << f_r(s,t) << endl;
}
system("PAUSE");
return 0;
}
int f_r(string str, string c)
{
int pos = 0;
pos = str.find(c, pos);
if (pos > str.length())
{
return 0;
}
else
{
pos++;
return pos - 1;
}
}