0

MyString::Find は、より大きな文字列内の文字列を検索し、部分文字列の開始位置を返します。文字列の位置は 0 から始まり、長さ -1 で終わることに注意してください。文字列が見つからない場合は、値 -1 が返されます。

MyString::Substring(開始、長さ)。このメソッドは、位置 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());
 }

コンパイルして実行すると、次のようになります。

文字列を 2 つ入力してください。各文字列は 256 文字未満にするか、 / で終了する必要があります。最初の文字列が検索され、2 番目の文字列が正確に含まれているかどうかが確認されます。

探す

である

ヒットの詳細:

ヒット開始位置: 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 に答える