【问题标题】:If statement provides false for only one string valueif 语句只为一个字符串值提供 false
【发布时间】:2021-06-19 08:16:57
【问题描述】:

大家好,我一直在尝试使用代码来提高我的编码技能。我遇到了一个“简单”的问题,并正在尝试自己的解决方案。在此过程中,我发现了一些令人惊讶的事情。

我的 if 语句为“c”字符串提供了一个错误值,但适用于所有其他字符串,我尝试检查其他字符串值并且它们有效。为什么我的代码为此语句提供了错误的结果?

这是我的代码

    string allowed ="abc";
    vector<string> words = 
    {
    "a",
    "b",
    "c",
    "ab",
    "ac",
    "bc",
    "abc"
    };
    
    int count = 0;
    bool contains;
    
    for(string w: words)
    {
        for(auto c: w)
        {
            if(allowed.find(c) <= w.size())
            {
              contains = true;  
            }else
            {
                contains = false;
                break;
            }
                
        }
        
        if(contains)
        {
            count++;   
        }
    }
    
    return count;

我的问题是为什么我的代码为“c”字符串提供了错误的结果? 还是我的 if else 语句有问题。

我该如何解决这个问题?

非常感谢所有帮助过我的人!

【问题讨论】:

  • 请阅读std::string.find()的手册,看看返回值是多少。此外,allowed.find(c) &lt;= w.size() 看起来不像您想要进行的比较。

标签: string c++11 if-statement char


【解决方案1】:
if(allowed.find(c) <= w.size())

这会在字符串allowed 中搜索字符c,如果找到,则将该字符的返回索引与字符串w 的长度进行比较。所以当wallowed短并且找到的字符在字符串中比w的长度晚时,即使找到它也会返回false。

你可能打算写

if(allowed.find(c) < allowed.size())

甚至更好

if(allowed.find(c) != string::npos)

让意图更清晰。

【讨论】:

    猜你喜欢
    • 2013-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-10
    • 2021-01-07
    • 2015-02-05
    • 2017-06-01
    • 2021-07-07
    相关资源
    最近更新 更多