代码之家  ›  专栏  ›  技术社区  ›  l. schwarz

为什么程序不能在字符串中手动查找附加的“#”(hashtags)?

  •  -1
  • l. schwarz  · 技术社区  · 8 年前

    运行此程序时:

    #include <cstdlib>
    #include <iostream>
    #include <string>
    
    using namespace std;
    
    int main(int argc, char** argv)
    {
        if (argc != 2)
        {
            cerr << "[ERR] usage: " << argv[0] << " expression" << endl;
            return 1;
        }
    
        string pExpression = argv[1];
    
        size_t stringLength = pExpression.length();
    
        if (pExpression[stringLength - 1] != '#') //If there is no hashtag at the end, append one
            pExpression += '#';
    
        cout << "Search for '#' in '" << pExpression << "'..." << endl;
    
        bool found = false;
    
        for (size_t i = 0;i < stringLength;i++)
        {
            if (pExpression[i] == '#')
                found = true;
        }
    
        cout << ((found) ? "String contains '#'" : "String doesn't contain '#'") << endl;
        return 0;
    }
    

    我试着检查,是否在末尾有一个标签。如果没有,我会附加一个。

    然而,如果我检查它,我的程序“找不到”它。

    下面是一个关于我的意思的例子:

    image

    1 回复  |  直到 8 年前
        1
  •  4
  •   Michel de Ruiter    8 年前

    因为你没有增加 stringLength 添加 # .所以 for 循环就停在它的正前方。