C 回文函数

新手上路,请多包涵

代码

#include <iostream>
#include <string>
using namespace std;

bool isPalindrome(string str)
{
    for(int i = 0; i <= str.length()-1; i++)
    {
        if(str[i] != str[str.length()-1-i])
        {
            return false;
        }
        else
        {
            return true;
        }
    }
}

int main()
{
    string text;

    do
    {
        cout << "Enter some Text: " << endl;
        cin >> text;
        if(isPalindrome(text))
        {
            cout << "The text is a palindrome" << endl;
        }
        else
        {
            cout << "The text is not a palindrome" << endl;
        }

    }while(text != "Q");

    return 0;
}

输入_1

 otto

输出

The text is a palindrome

输入_2

  ottop

输出

The text is a palindrome

输入_3

 ottopo

输出3

 The text is a palindrome

我想检查用户输入的字符串是否为回文?为什么我的第三个输入的输出出错了?我想我错过了一些东西。

原文由 user5539363 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 298
1 个回答

您在循环的第一次迭代中返回 true。你只需要迭代一半的字符串。

更正:

     size_t len = str.length();

    for(int i = 0; i < len/2; i++){
        if(str[i] != str[len-1-i]){
            return false;
        }
    }
    return true;

原文由 selbie 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题