C++ char class findCharIndex

问题描述 投票:1回答:1
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"。

"我有两只狗 "中 "2 "的第一个索引是-1.

请告诉我为什么它应该是7?

c++ class character c-strings
1个回答
4
投票

你的 return -1; 语句的位置不对。

它附属于 elseif 循环内,因此,当 this->operator[](i) == c 评价为false。 实际上,如果第1个 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
}
© www.soinside.com 2019 - 2024. All rights reserved.