错误错误输出

用户名

我有一个密码。假设每次找到“代码”,“应付”,“结束”,“科尔”或“核心”时,都会给我输出计数的数量。例如:countCode(“ aaacodebbb”)应该为1,但发现为0。

int countCode(const string& inStr) {
    int count = 0;
    for (unsigned i = 0; i < inStr.length(); i++) {
        if (inStr.substr(i,i+3) == "code" || inStr.substr(i,i+3) == "coze" || inStr.substr(i,i+3) == "cope" || inStr.substr(i,i+3) == "core" || inStr.substr(i,i+3) == "cole") {
            count++;
        }
    }
    return count;
}
紫罗兰色
string substr (size_t pos = 0, size_t len = npos) const;

第二个参数是长度,而不是最终的字符位置。您需要inStr.substr(i,4)改用。

此外,您知道当字符串中剩余的字符数少于四个时,就不会出现四个字符的字符串,因此可以通过以下方式使其变得更逻辑(并且可能更有效):

int countCode (const string& inStr) {
    int count = 0;
    size_t len = inStr.length();
    if (len >= 4) {
        for (size_t i = 0; i <= len - 4; i++) {
            if (inStr.substr(i,4) == "code" || ... ) {
                count++;
            }
        }
    }
}

还要注意,使用size_t它是更自然的类型来处理字符串中的大小和位置。

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章