我正在尝试编写一个代码,该代码将在 userInput 中搜索单词“darn”,如果找到,则打印出“Censored”。如果没有找到,它只会打印出 userInput。它在某些情况下有效,但在其他情况下无效。如果 userInput 是“那该死的猫!”,它会打印出“Censored”。但是,如果 userInput 是“Dang,那太可怕了!”,它还会打印出“Censored”。我正在尝试使用 find() 来搜索字符串文字“darn”(空格是因为它应该能够在“darn”这个词和“darning”之类的词之间确定。我不担心“darn”之后的标点符号”)。但是,似乎 find() 没有做我想做的事。还有另一种方法可以搜索字符串文字吗?我尝试使用 substr() 但我无法弄清楚索引和 len 应该是什么。
#include <iostream>
#include <string>
using namespace std;
int main() {
string userInput;
userInput = "That darn cat.";
if (userInput.find("darn ") > 0){
cout << "Censored" << endl;
}
else {
cout << userInput << endl;
} //userText.substr(0, 7)
return 0;
}
最佳答案
这里的问题是你的情况。 std::string::find
返回一个 std::string::size_type
的对象,它是一个无符号整数类型。这意味着它永远不会小于 0,这意味着
if (userInput.find("darn ") > 0)
将始终为 true
除非 userInput
以 "darn "
开头。因此,如果 find
没有找到任何东西,那么它会返回 std::string::npos
。你需要做的是与类似的东西进行比较
if (userInput.find("darn ") != std::string::npos)
请注意 userInput.find("darn ")
并非在所有情况下都有效。如果 userInput
只是 "darn"
或 "Darn"
那么它将不匹配。空间需要作为一个单独的元素来处理。例如:
std::string::size_type position = userInput.find("darn");
if (position != std::string::npos) {
// now you can check which character is at userInput[position + 4]
}
关于c++ - 如何查找子字符串或字符串文字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46100569/