0

MyString::Find 在较大的字符串中查找字符串并返回子字符串的起始位置。请注意,您的字符串位置从 0 开始,以长度 -1 结束。如果未找到该字符串,则将返回值 -1。

MyString::Substring(开始,长度)。此方法返回原始字符串的子字符串,该子字符串包含与从位置 start 开始的原始字符串相同的字符,并且与长度一样长。

我在 .cpp 文件中的功能是:

  MyString MyString::Substring(int start, int length)
 {
    char* sub;
    sub = new char[length+1];


    while(start != '\0')
    {
            for(int i = start; i < length+1; i++)
            {
                    sub[i] = String[i];
            }
    }
    return MyString(sub);
 }


 const int MyString::Find(const MyString& other)
 {
    int start(0);

    int counter(0);

    int end = other.Size;

    int end1 = Size;

    int nfound = -1;

   if(end > end1)
    {
            return nfound;
    }
    int i = 0, j = 0;
    for(i = 0; i < end1; i++)
    {
            for(j = 0; j < end; j++)
            {
                    if( ((i+j) >= end1) || (String[i+j] != other.String[j]) )
                    {
                            break;
                    }




            }
            if(j == end)
            {
                    return i;
            }




    }

    return nfound;

   }

main.cpp文件中的函数调用如下:

      cout << "Please enter two strings. ";
      cout << "Each string needs to be shorter than 256 characters or terminated by /\n." << endl;
     cout << "The first string will be searched to see whether it contains exactly the second string. " << endl;

     cin >> SearchString >> TargetString; // Test of cascaded string-extraction operator



     if(SearchString.Find(TargetString) == -1) {
       cout << TargetString << " is not in " << SearchString << endl;
  } else {
       cout << TargetString << " is in " << SearchString << endl;
       cout << "Details of the hit: " << endl;
       cout << "Starting poisition of the hit: " << SearchString.Find(TargetString) << endl;
       cout << "The matching substring is: " << SearchString.Substring(SearchString.Find(TargetString), TargetString.Length());
 }

编译并运行后,我得到:

请输入两个字符串。每个字符串必须少于 256 个字符或以 / 结尾。将搜索第一个字符串以查看它是否正好包含第二个字符串。

寻找

在找到

命中详情:

命中起始位置:1 ^C

我最终不得不使用控制 C 中止程序,但我确信我的代码有问题,我根本没有看到。请帮忙!我究竟做错了什么?

4

1 回答 1

0

问题在于 Substring 方法。您正在使用一个永远持续的 while 循环。您可能正在寻找类似以下代码段的内容。

 MyString MyString::Substring(int start, int length)
 {
    char* sub;
    sub = new char[length+1];

    for(int i = start; i < length+1; i++)
    {
        sub[i] = String[i];
    }

    return MyString(sub);
 }
于 2012-06-15T18:57:20.427 回答