子串和查找方法错误处理

时间:2012-06-15 01:48:00

标签: string oop error-handling substring

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

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

我在.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个字符或由/终止 。 将搜索第一个字符串以查看它是否包含完全第二个字符串。

查找

in is in find

点击详情:

开始击中击球:1 ^ C

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

1 个答案:

答案 0 :(得分: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);
 }