我需要在C ++中构建一些单词搜索功能,但似乎它不起作用。任何线索?

时间:2013-11-13 05:19:48

标签: c++

下面是我编写的代码,if语句用于确定单词在句子中的天气,但是想要有一个函数。任何人都可以检查这个和什么

#include <iostream>
#include <cstdio>
#include <string> 
#include <iomanip> 

using namespace std;

int main ()
{
char sentence[50]; 
char search [50];
int numtimes = 0;

cout << "Enter a sentence: " << endl; 
gets_s (sentence); 
cout << endl; 
cout << "Your sentence is: \n" << sentence << endl;


cout << "Enter a any word: " << endl;
gets_s (search);
cout << endl;
cout << "The word is: " << search << endl;

int i, len;
int j, lenS;
len = strlen(sentence); 
lenS = strlen(search);


for (i = 0; i < len - lenS + 1; i++)
{
    if (sentence[i] == search[0])
    {
        for (j = 0; j < lenS; j++)
        {
            if (sentence[i+j] != search[j])
                break; 
        }
        if (j == lenS)
        {
            cout << "search found\n";
            break;
        }
    }
}

if (i == len - lenS +1)
{
    return 1;
}



system("PAUSE"); 
return 0; }

1 个答案:

答案 0 :(得分:0)

我想你需要这个来研究函数和参数。我对您的代码进行了少量更改,只是为了展示如何将代码放入函数中。

#include <iostream>
#include <cstdio>
#include <string>
#include <iomanip>

using namespace std;

// the function is here
bool searchWord(char* sentence, char* search)
{
    int i, len;
    int j, lenS;
    len = strlen(sentence);
    lenS = strlen(search);

    bool found = false;
    for (i = 0; i < len - lenS + 1; i++)
    {
        if (sentence[i] == search[0])
        {
            for (j = 0; j < lenS; j++)
            {
                if (sentence[i+j] != search[j])
                    break;
            }
            if (j == lenS)
            {
                //cout << "search found\n";
                found = true;
            }
        }
    }

    if (i == len - lenS +1)
    {
        found = false;
    }

    return found;
}

int main ()
{
    char mySentence[50];
    char mySearch [50];
    int numtimes = 0;

    cout << "Enter a sentence: " << endl;
    gets (mySentence);
    cout << endl;
    cout << "Your sentence is: \n" << mySentence << endl;


    cout << "Enter a any word: " << endl;
    gets (mySearch);
    cout << endl;
    cout << "The word is: " << mySearch << endl;

    if (searchWord(mySentence, mySearch)) {
        cout << "Found\n";
    }
    else
    {
        cout << "Not Found\n";
    }

    system("PAUSE");
    return 0; 
  }   

有两点需要注意:

  1. 您可能需要在找到单词的最后一个字母后检查空格。例: 句子:句子应该是英语 单词:句子

  2. string.h有几个功能,可以在这类任务中使用。