我试图弄清楚如何删除空格,然后检查删除空格的字符串是否是回文。
我已经分别尝试了这两件事,但我无法让它们一起工作。
int check_palindrome(char *);
int main()
{
char s1[20];
printf("Enter the string...\n");
gets(s1);
int x;
x=check_palindrome(s1);
x?printf("%s = is a Palindrome\n", s1):printf("%s = is Not a Palindrome\n", s1);
}
int check_palindrome(char *s)
{
int i,j;
for(i=0;s[i];i++);
for(i=i-1,j=0;i>j;i--,j++)
{
if(s[i]!=s[j])
{
return 0;
}
}
if(s[i]==s[j])
{
return 1;
}
}
此代码适用于检查回文,但如果输入以大写字母开头或包含空格,则该代码不起作用。例如,我希望“nurses run”的输出为“nurses run is a palindrome”,但实际输出是“nurses run is not a palindrome”,因为中间有空格,而“Dad”的预期输出是“爸爸是回文”,但它返回“爸爸不是回文”。
如果您不需要修改后的字符串,您可以节省大量工作,只需在比较中忽略空格和大小写,例如:
int ispalindrome = 1;
while (s < e && ispalindrome) {
while (*s == ' ') s++;
while (*e == ' ') e--;
if (tolower(*s++) != tolower(*e--))
ispalindrome = 0;
}
with s
指向开始并e
指向字符串的末尾(最后一个字符)。
Edit:
我刚刚意识到,如果整个字符串仅由空格组成,则存在一种极端情况,可能会发生越界数组访问。然后第二个空格跳跃循环将经过数组的“左”端。所以将其更改为
while (*e == ' ' && e > s) e--;
请注意,在这种情况下,ispalindrome
将会是假的。这是一个定义问题,如果empty字符串是否是回文。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)