【问题标题】:Search string for a given word and return a boolean value搜索给定单词的字符串并返回一个布尔值
【发布时间】:2012-07-29 23:50:05
【问题描述】:

我是这个网站的新手,我想问一下是否有人知道如何解决我的问题。 我已经在网上搜索了几个小时,但没有找到任何适合我的东西。 任何帮助将不胜感激。

1) 我必须编写一个要求输入单词的函数。
2) 将此单词添加到数组中。
3) 如果一个词与给定的词匹配,则搜索一个字符串。
4) 布尔返回值,如果为真,否则为假。

到目前为止,我对我的功能做了什么。所以我相信我已经接近它了(我只需要 for 循环来搜索这个词)。

bool checkValidTitle( string modules[MODULENO+1]){
    string array[1][20];
    cout<< "Put the module: ";
    cin>> array[1][20]; 
}

【问题讨论】:

  • 您确定您的问题是关于 C 而不是 C++?您列出的代码是 C++ 代码,而不是 C。对于 C++,您确实可以使用 std::string::find
  • 它的 c++ 我不知道为什么标题没有显示“++”谢谢你的快速回复更新:添加了“++”:) 谢谢
  • 为什么要有本地数组?你只需要一个字符串。
  • 我需要将用户放入的单词放入一个数组中

标签: c++ string


【解决方案1】:

这是你被要求编写的函数

bool checkValidTitle(string modules[], string word_to_check)
{
  for (int i = 1; i <= MODULENO; ++i)
    if (modules[i] == word_to_check)
       return true;
  return false;
}

这样使用

string modules[MODULENO+1] = {"", "Maths", "Sciences", "French", "English"};
if (checkValidTitle(modules, "Maths"))
   cout << "Maths is valid\n";
else
   cout << "Maths is not valid\n";
if (checkValidTitle(modules, "Russian"))
   cout << "Russian is valid\n";
else
   cout << "Russian is not valid\n";

剩下的就交给你了。

【讨论】:

    【解决方案2】:

    那天我写了一个函数,如果第一个字符串包含第二个字符串,则返回一个布尔值:

    bool contains(const std::string & str, const std::string substr)
    {
        if(str.size()<substr.size()) return false;
    
        for(int i=0; i<str.size(); i++)
        {
            if(str.size()-i < substr.size()) return false;
    
            bool match = true;
            for(int j=0; j<substr.size(); j++)
            {
                if(str.at(i+j) != substr.at(j))
                {
                    match = false;
                    break;
                }
            }
            if(match) return true;
        }
        return false;
    }
    

    我已经测试了一段时间,它似乎工作。它用蛮力搜索,但我尽量优化。

    使用这个方法你可以做到:

    std::string main_str = "Hello world!";
    std::string sub_str = "ello";
    std::string sub_str2 = "foo";
    
    bool first = contains(main_str, sub_str); //this will give you true
    bool second = contains(main_str, sub_str2); //this will give you false
    

    现在我不太明白,你想要的字符串数组是什么,但我认为,有了这个,你可以获得所需的输出。

    【讨论】:

      猜你喜欢
      • 2021-10-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-26
      • 2015-12-18
      • 2014-06-28
      • 1970-01-01
      相关资源
      最近更新 更多