C++ 如何使用string::find()?

C++ 如何使用string::find()?,c++,C++,如果userInput包含单词“darn”,则打印“已审查”,否则打印userInput。以换行结束。提示:如果未找到要搜索的项目,find()将返回string::npos 注意:这些活动可能使用不同的测试值测试代码。此活动将执行三个测试,用户输入“那该死的猫”,然后输入“该死,那太可怕了!”,然后输入“我正在给你补袜子” 这是我试过的代码。我真的不知道还能尝试什么 #include <iostream> #include <string> using namespac

如果userInput包含单词“darn”,则打印“已审查”,否则打印userInput。以换行结束。提示:如果未找到要搜索的项目,find()将返回string::npos

注意:这些活动可能使用不同的测试值测试代码。此活动将执行三个测试,用户输入“那该死的猫”,然后输入“该死,那太可怕了!”,然后输入“我正在给你补袜子”

这是我试过的代码。我真的不知道还能尝试什么

#include <iostream>
#include <string>
using namespace std;

int main() {
   string userInput;

   userInput = "That darn cat.";

   if (userInput.find("darn")) {
      cout << "Censored" << endl;
   }

   else {
      cout << userInput << endl; 
   }

   return 0;
}
#包括
#包括
使用名称空间std;
int main(){
字符串用户输入;
userInput=“那个该死的猫。”;
if(userInput.find(“darn”)){
难道你没有按照别人给你的指示去做吗。
具体而言,您缺少以下条件的代码:

  • 提示:如果未找到要搜索的项目,find()将返回string::npos

    您没有检查
    npos
    (定义为
    string::size\u type(-1)
    )的
    find()
    的返回值

    find()

    语句
    if(userInput.find(“darn”)
    正在检查零索引值与非零索引值。在所有三个测试用例中,
    find()
    不会返回索引0,因此任何非零值都会导致
    if
    语句的计算结果为
    true
    ,并且将输入
    “删失的”

  • 此活动将执行三个测试,用户输入“那该死的猫”,然后输入“该死,那太可怕了!”,然后输入“我正在给你补袜子”

    您只执行第一个测试,而不执行其他测试

请尝试以下方法:

#include <iostream>
#include <string>
using namespace std;

int main() {
    string userInput;

    userInput = "That darn cat.";

    if (userInput.find("darn") != string::npos) {
        cout << "Censored" << endl;
    }
    else {
        cout << userInput << endl;
    }

    userInput = "Dang, that was scary!";

    if (userInput.find("darn") != string::npos) {
        cout << "Censored" << endl;
    }
    else {
        cout << userInput << endl;
    }

    userInput = "I'm darning your socks.";

    if (userInput.find("darn") != string::npos) {
        cout << "Censored" << endl;
    }
    else {
        cout << userInput << endl;
    }

    return 0;
}
#包括
#包括
使用名称空间std;
int main(){
字符串用户输入;
userInput=“那个该死的猫。”;
if(userInput.find(“darn”)!=string::npos){

看不见。问题的文本告诉您遗漏了什么-“
find()
如果未找到要搜索的项目,则返回
string::npos
。”您没有对照
string::npos
检查它返回的内容。
#include <iostream>
#include <string>
using namespace std;

void checkInput(const string &input) {
    if (input.find("darn") != string::npos) {
        cout << "Censored" << endl;
    }
    else {
        cout << input << endl;
    }
}

int main() {
    string userInput;

    userInput = "That darn cat.";
    checkInput(userInput);

    userInput = "Dang, that was scary!";
    checkInput(userInput);

    userInput = "I'm darning your socks.";
    checkInput(userInput);

    return 0;
}