我正在编写回文代码来检查给定的字符串是否是回文。例如:妈妈,1001...
MY_CODE:
#include <stdio.h>
#include <stdlib.h>
#include <stdio_ext.h>
int main()
{
int i,n;
char p[999];
char flag;
printf("number of characters in the strings");
scanf("%d",&n);
printf("Enter string: ");
for (i=0;i<n;i++)
{
printf("\n");
__fpurge(stdin);
scanf("%c",&p[i]);
}
for (i=0;i<n;i++)
{
if (p[i]==p[n-1-i])
{
flag=0;
break;
}
else flag=1;
}
if (flag==1)
printf("It's not a palindrome");
if (flag==0)
printf("It's a palindrome.");
return 0;
}
我试图这样做的想法是,如果最后一个和第一个字符匹配,对于下一个字符依此类推。如果它们全部匹配,则字符串是回文,否则不是,就这么简单,但我的输出 显示 123;妈妈;每一个废话都是一个回文(“甚至是‘废话’这个词:D)。
有人可以指导我吗?
P.S.:我是一个新手,正在学习 C。我的操作系统:Ubuntu 15.10。
最佳答案
您正在检查字符是否相同,设置 flag=0 表示它是回文,但这会发生在第一个匹配中 - 如果其他匹配没有发生,则该标志永远不会设置为不是一个回文。
更好的方法是假设它是回文,然后如果有其他情况,将其设置为 false。
#include <stdio.h>
#include <string.h>
int main()
{
char p[999];
printf("Enter string: ");
if(fgets(p, sizeof(p), stdin))
{
int palindrome = 1;
int i;
int n;
n = strlen(p);
/* handle new line at end of fgets input */
if(p[n-1] == '\n')
p[n-1] = '\0';
n = strlen(p);
/* 0 length string (after newline removed) - not a palindrome */
if(n == 0) palindrome = 0;
for(i=0;i<n/2;i++)
{
/* look for a chatacter pair that doesn't match - if find, then we don't have a palindrome */
if(p[i] != p[n-1-i])
palindrome = 0;
}
if(palindrome)
printf("is a palindrome\n");
else
printf("is not a palindrome\n");
}
return 0;
}
关于c - C 中的回文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38059418/