C++ 搜索子串

C++ 搜索子串,c++,substring,C++,Substring,我是一名编程专业的学生。我被要求编写一个程序来搜索另一个字符串的子字符串,但我不打算使用string类中提供的find()函数。到目前为止,我编写的代码仍然有效,但它使用了find()函数。我如何才能将其更改为不使用find函数,并且仍然提供子字符串的位置?这是我的密码: #include <iostream> #include <string> using namespace std; int f_r(string, string);

我是一名编程专业的学生。我被要求编写一个程序来搜索另一个字符串的子字符串,但我不打算使用string类中提供的
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;
        }

     }
#包括
#包括
使用名称空间std;
int f_r(字符串,字符串);
int main()
{
字符串s;
字符串t;
库特;
如果(f_r(s,t)==0)
{

cout您需要在字符串中搜索匹配项,每次搜索一个字符,也就是说,将字符串视为字符数组(因为您显然是在C/C++中工作,这非常方便,因为
string
char[]
是同义词)

您可能需要在两个字符串中维护指向当前位置的索引或指针

这将是一种幼稚的/初步的方法,当你工作得相当好时,假设你有点好奇,你会开始怀疑是否有更有效的方法来做到这一点,例如在某些情况下跳过一些字符,或者使用有关底层语言中文本的一般统计信息

int search(char *a,char *b)
{
  int i=0,j=0,k=0,m,n,pos;
  m=strlen(a);
  n=strlen(b);
  while(1)
  {
    while((a[i]==b[j]) && b[j]!=0)
   {
     i++;
     j++;    
   }
   if (j==n)
   {
     pos=i-j;
     return(pos);
   }
   else
  {
     i=i-j+1;
     j=0;
  }
}}
我随身带着这个密码。我希望它能帮助你

注意:-这是一个旧代码

此艺术可能有助于:

|_|_|_|_|_|_|_|_|_|_|_|
     ^   ^
     i  i+j 
         | 
    |_|_|_|_| 
         ^
         j

你有没有试过自己编写一个替换的
find
函数?如果有,你写了什么?顺便说一句,我相信你已经学会了这一点,但是模式匹配的最佳算法之一是Rabin Karp。你可以在wikipidia上读到:通常当OP的问题暗示事实上,我只是注意到解决方案并不像看上去的那么完整:存在一些错误,特别是当找不到字符串时缺少显式返回、未使用的变量以及变量名选择不当。[很抱歉吹毛求疵,但如果我们要帮助下一代,让我们给他们一个好的例子和好的习惯]我只是在为他们指路。只是如何移动。这只是基本的代码。我说“这是一个旧代码”。顺便说一句,谢谢你的评论,我会记住它的。