int String::findCharIndex(const char &c) const
{
for (int i =0; i < this->getLength();i++)
{
if ( this->operator[](i) == c)
{
return i;
break;
}
else
return -1;
}
我一直在使用此函数在c字符串中返回字符c的索引。该函数可以很好地处理字符,但是如果c是数字,则结果仍为-1。
例:
“我有2条狗”中的第一个索引“2”是-1。
请告诉我为什么,因为它应该是7?
最佳答案
您的return -1;
语句在错误的位置。
它被附加到循环内else
的if
上,因此当this->operator[](i) == c
评估为false时将达到该值。实际上,如果第一个char
是匹配项,则调用return i;
,否则调用return -1;
。您将完全忽略第二个及后续char
。return -1;
语句需要移动到循环下方,以便仅在扫描整个字符串而未找到任何匹配项时才到达该语句
int String::findCharIndex(const char &c) const {
for (int i = 0; i < this->getLength(); ++i) {
if (this->operator[](i) == c) {
return i;
}
}
return -1; // <-- moved here
}
关于c++ - C++ char类findCharIndex,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62187490/