#include <iostream>
#include <string.h>
using namespace std;
int main()
{
int len;
char char1[100],char2[100];
cout << "Enter a word:" << endl;
cin >> char1;
len = strlen(char1);
for(int i=0;i<len;i++)
{
char2[i] = char1[len-i-1];
}
if(strcmp(char1,char2))
{
cout << "It is not a palindrome." << endl;
}
else
{
cout << "It is a palindrome" << endl;
}
}
我试着编写一个代码来查找单词是否是回文。当我输入“女士”作为输入时,输出是“它是回文”。但是当我输入“爸爸”作为输入时,输出是“它不是回文”。为什么?
因为这里使用字符数组来表示字符串,并且strcmp
用于比较这些数组,您需要记住文本的最后一个值必须是'\0'
(也称为空字符/空终止符)。
所以在循环后,反向复制字符串,需要添加以下内容;
char2[len] = '\0';
当使用strcmp
时,应该明确地显示它正在检查的条件。原因是strcmp
返回3个结果(-1
,0
,1
),并且从您的代码中,如果正确使用API,它应该是直接可见的。 (即使C和C ++将值隐式转换为bool)
与直觉相反,当比较的弦不同时(strcmp
和true
),-1
的结果将转换为1
,当它们相同时(false
)转换为0
。
条件应该是,例如:
if (strcmp(char1, char2) == 0) // checking if strings are equal
要么
if (strcmp(char1, char2) != 0) // checking if strings are different
在像这里一样的函数结果的模糊情况下,甚至建议创建一个临时(常量)布尔变量以使代码更容易理解。像这样:
const bool is_palindrome = (strcmp(char1, char2) == 0);
if (is_palindrome)
// ...
这是另一个提议,如何实现此算法:
#include <iostream>
#include <string>
int main()
{
using namespace std;
cout << "Enter a word:" << endl;
string input_str;
getline(cin, input_str);
const string reversed_str(input_str.rbegin(), input_str.rend());
const bool is_palindrome = (input_str == reversed_str);
if (is_palindrome)
{
cout << "It is a palindrome" << endl;
}
else
{
cout << "It is not a palindrome." << endl;
}
}