C++ 将字符串与单词进行比较

标签 c++ string compare

我正在尝试构建一个程序,该程序接受用户输入的单词,然后将其转换为数字以便系统工作。

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 ,而不是一长串 ifelse 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/

相关文章:

python - 是否有 Python 模块来解析原始字符串中的换行符符号?

ORDER BY 在结构上的 C++ 实现

python - 在 python 中使用 id() 比较列表(整数)

c++ - 派生类如何使用基类的 protected 成员?

c++ - 是否可以从 stdin 输入指向指针的地址?

regex - 在同一位置查找和替换匹配的字母

python - 如何比较两个具有 NaN 值的 numpy 数组?

c++ - 在编译器选项中定义字符串

c++ - 将指向成员的指针从模板参数包传递给函数对象

javascript - 将 Javascript 字符串传递给 php 字符串