如何使用 string::find()?
How to use string::find()?
打印"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;
}
相关文章:
- 在先前调用 string::find 后添加内存分配和内存集会导致它返回 npos.为什么?
- std::string::find 为取消引用的迭代器和等效字符串文本返回不同的值
- string.find() 无法正常工作
- std::string::find 返回错误的答案
- std::string::find 总是返回 string::npos 偶数
- 使用"std::search"而不是"string::find"
- 如何使用 string::find()?
- String.find() 在 C++ 中找不到任何内容时不会返回 -1
- 使用 std::find 查找从二进制文件中读取的字符并转换为 std::vector 中的 std::string<string> 会产生这种不可预测的行为?
- 在无序映射<字符串上使用 find(),向量<string>>与 C++ 中的有序映射花费相同的时间
- 使用 std::string::find 在一个小字符串中查找较长的字符串
- 使用 string::find 来解析文件
- 如何使用 string::find 在一个操作中查找"+"或"-"
- std::find on std::vector< std::string > 在 Visual C++ 2008 中无法编译?
- 应对"Find the first repeated character in a string"挑战的最紧凑、高效、可读和智能的解决方案
- 使用 string::find 和 string::substr 拆分字符串的函数返回错误的标记
- std::string::find在c++中未按预期工作
- 性能比较:strstr()与std::string::find()
- Android-NDK 的 GGC/C++ 对于 std::string::find/std::getline(...) 来说似乎不稳定
- 使用 C++11 编译 UI 代码时面临"unable to find string literal operator"错误