如何使用 string::find()?

How to use string::find()?

本文关键字:find string 何使用      更新时间:2023-10-16

打印"Censored",如果用户输入包含单词"darn",否则打印userInput。以换行符结尾。提示:find() 返回字符串::npos 如果未找到要搜索的项目。

注意:这些活动可能会使用不同的测试值测试代码。此活动将执行三个测试,用户输入"那的猫",然后是"Dang,这太可怕了!",然后是"我正在破坏你的袜子"。

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

#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;
}

如果包含"darn"userInput应导致Censored。否则,它应该打印userInput

我的结果显示每个输入Censored

您没有遵循给出的指示。

具体来说,您缺少以下条件的代码:

  • 提示:find() 返回字符串::npos 如果未找到要搜索的项目。

    您没有检查find()的返回值以获取npos(定义为string::size_type(-1))。

    find()返回找到的子字符串的索引的数值,如果未找到,则返回npos

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

  • 此活动将执行三个测试,用户输入"那的猫",然后是"Dang,这太可怕了!",然后是"我正在破坏你的袜子"。

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

试试这个:

#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;
}

然后可以使用可重用函数重写:

#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;
}