0

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

     }
4

3 回答 3

1

您需要一次在字符串中搜索一个字符,即将字符串视为字符数组(因为您显然在使用 C/C++ 工作,这非常方便,string并且char[]是同义词)。

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

这将是幼稚/初始的方法,当你让它工作得很好时,假设你有点好奇,你会开始想知道是否有更有效的方法来做到这一点,例如在某些情况下跳过一些字符,或通过使用有关基础语言文本的一般统计数据。

于 2012-10-27T04:29:53.267 回答
0

这种艺术可能有助于:

|_|_|_|_|_|_|_|_|_|_|_|
     ^   ^
     i  i+j 
         | 
    |_|_|_|_| 
         ^
         j
于 2012-10-27T07:06:05.153 回答
-1
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;
  }
}}

我有这个代码。我希望它会帮助你。

注意:-它是旧代码

于 2012-10-27T04:32:03.640 回答