我正在尝试构建一个程序,该程序需要用户输入单词,然后将其转换为数字以使系统正常工作。
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”吗?有没有一种方法可以不必将每个“特定单词”都设置为自己的字符串?
感谢
考虑此示例:
std::string str = "Hello world, what's up today on SO?";
if (str.find("world") != std::string::npos)
return 1;
else if (str.find("what's up") != std::string::npos)
return 2;
else
return 0; // or something
这里我们使用std::string::npos
来查看指定的单词在字符串的最后是否存在。如果是,则按照您的要求为将来分配一个值。
if (WordInput.find("Specific Word"))
std::string::find()
返回类型为std::string::find()
的值。它为您提供搜索词在字符串中的位置。如果找不到搜索字符串,则返回size_t
。
代替一长串的string::npos
和if
语句,您可以在此处使用映射。查找将更快,并且如果使用else if
,它将为O(1)(恒定时间)。
因此您的功能可以简化为:
std::unordered_map
此处地图中的每个条目都是一对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;
}
。如果找到给定的单词,则返回相应的int,否则返回0。
工作版本(string, int)
。