【问题标题】:I want to check whether a string is palindrome [closed]我想检查一个字符串是否是回文[关闭]
【发布时间】:2017-08-23 13:00:09
【问题描述】:
char s[100];
//char t[100];
int count = 1;
int j=0;
int x,i;
cin >>s;
x=strlen(s);
//cout <<x <<endl;
cout <<s[j] <<endl;
i=x-1;
cout <<s[i] <<endl;
for (int i = x-1; i <= 0; i--)
{
    if (s[j] != s[i])
    {
        count = 0;
    }
    j++;

}
if ( count  )
{
    cout <<"YES";
}
else
{
    cout <<"NO";
}
return 0;

我想知道给定的字符串是否是回文。这段代码有什么问题?如果正在输入回文,我希望它打印 YES,如果字符串不是回文,则打印 NO。但它总是打印 YES。没有错误。

【问题讨论】:

  • 欢迎来到 Stack Overflow!您能否详细说明您的代码如何“不起作用”?你期待什么,实际发生了什么?如果您遇到异常/错误,请发布它发生的行和异常/错误详细信息。请edit这些详细信息,否则我们可能无法提供帮助。
  • 条件i &lt;= 0 从一开始就是假的。循环永远不会运行。
  • for (int i = x-1; i &lt;= 0; i--):这个循环只要i &lt;= 0,只有当你输入一个空字符串或一个字符的字符串时才会发生。因此 for 循环永远不会运行,count 始终是 1

标签: c++11 for-loop if-statement palindrome


【解决方案1】:

您的代码永远不会输入for loop,因为条件i = x-1 and i &lt;=0 不会是正确的assuming your string is not empty,因此无需保留计数变量,因为一旦字符串不匹配,您就可以打印 NO 和退出代码。

你可以像这样实现它:

#include <iostream>

using namespace std;

int main() {
    char s[100];
    int x,i,j=0;
    cin >>s;
    x=strlen(s);
    i = x-1;
    cout <<s[0] <<endl;
    cout <<s[i] <<endl;
    for (int i = x-1; i >= 0; i--)
    {
        if (s[j] != s[i])
        {
            cout <<"NO";
            return 0;
        }
        j ++;
    }
    cout <<"YES";
    return 0;
} 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-05-24
    • 2019-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-26
    • 2011-02-02
    相关资源
    最近更新 更多