c - 如何删除空格并检查字符串是否是回文?

标签 c

我试图找出如何删除空格,然后检查删除空格的字符串是否是回文。

我已经分别尝试了这两件事,但无法让它们一起工作。

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;
}

其中 s 指向字符串的开头,e 指向字符串的结尾(最后一个字符)。

编辑:

我刚刚意识到,如果整个字符串仅由空格组成,则存在一种极端情况,可能会发生越界数组访问。然后第二个空格跳跃循环将经过数组的“左”端。所以将其更改为

        while (*e == ' ' && e > s) e--;

请注意,在这种情况下,ispalindrome 将为 false。 字符串是否是回文是一个定义问题。

关于c - 如何删除空格并检查字符串是否是回文?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55412667/

相关文章:

c - 从 C 中的文件扫描

c - 如何翻转和反转 C 中的 int?

检查在填字游戏中水平或垂直放置单词的可能性

c++ - 如何在结构中嵌入 CUDA 纹理对象?

c - 如何将字符串数组传递给函数?

c - 网络过滤队列 : use --queue-balance in multithreaded environment

c - 艰难调试神秘的git+ssh+proxy失败 "bash: No such file or directory"

c++ - 尽可能在本地声明变量和 switch 语句

c - f将双向链表写入二进制文件段错误

c - 在 c 中一次处理多个连接