我有个密码。它假设每次找到“代码”、"cope“、"coze”、"cole“或"core”时,都给我一个计数的输出。例如: 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;
}发布于 2014-02-19 06:06:20
string substr (size_t pos = 0, size_t len = npos) const;第二个参数是长度,而不是最后的字符位置。您需要使用inStr.substr(i,4)代替。
此外,您还知道,如果字符串中剩余的字符少于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的使用,这是处理字符串中大小和位置的更自然的类型。
发布于 2014-02-19 06:05:59
如果您检查例如 reference,您将看到第二个参数是子字符串的长度,而不是结束位置。
发布于 2014-02-19 06:06:03
substr()的第二个参数是计数,而不是结束位置。
basic_string substr( size_type pos = 0,
size_type count = npos ) const;参数
pos - position of the first character to include
count - length of the substring
^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^也就是说,你应该用
inStr.substr(i,4)https://stackoverflow.com/questions/21872379
复制相似问题