我正在尝试构建一个程序,该程序接受用户输入的单词,然后将其转换为数字以便系统工作。
int FunctionName(string WordInput)
{
int ReferenceNumber;
if (WordInput.find("Specific Word"))
{
return ReferenceNumber = 0;
}
else if (WordInput.find("Specific Word 2"))
{
return ReferenceNumber = 1;
}
list goes on and has and else to get out.
现在,代码将进入第一个“if”语句,无论我将什么作为“WordInput”,它都会返回 0。
“.find”不能这样用吗?有没有办法做到这一点,而不必将每个特定单词作为自己的字符串?
谢谢
最佳答案
if (WordInput.find("Specific Word"))
std::string::find()
返回 size_t
类型的值。它为您提供搜索词在字符串中的位置。如果未找到搜索字符串,则返回 string::npos
。
您可以在此处使用 map ,而不是一长串 if
和 else if
语句。查找速度会更快,如果您使用 std::unordered_map
,它将是 O(1)(恒定时间)。
所以你的函数可以简化为:
int FunctionName(const std::string &word)
{
//Map of string and reference number
const static std::unordered_map<std::string, int> WordMap =
{ {"one", 1 }, { "two", 2 }, { "three", 3 } };
auto it = WordMap.find(word);
if (it != WordMap.end())
return it->second;
return 0;
}
这里映射中的每个条目都是一对(string, int)
。如果找到给定的单词,则返回相应的 int,否则返回 0。
工作版本here .
关于C++ 将字符串与单词进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61902070/