c - 如何在C中的回文代码中忽略符号和空格

标签 c

#include <stdio.h>
#include <string.h>

int main(int argc, char **argv) {

    int l = 0;
    char a[] = "Madam, I'm Adam.";
    int h = strlen(a) - 1;
    while (h > 1) {
        if (a[l++] != a[h--]) {
            printf("%s is not a palindrome\n", a);
            return 1;
        }    

    }

}

这适用于像“madam”这样没有任何符号的字符串。有没有办法忽略所有符号,例如“.”、“”、“'”,实际上是所有非字母数字字符。有办法让这个工作吗?

最佳答案

您可以使用 isalnum 函数来测试字母数字字符。如果您遇到不符合的情况,请根据需要增加/减少索引,直到找到符合的情况。

while (l<h) {
    while (!isalnum(a[l]) && l<h) l++;
    while (!isalnum(a[h]) && l<h) h--;
    if (tolower(a[l++]) != tolower(a[h--])) {
        printf("%s is not a palindrome\n", a);
        return 1;
    }
}
printf("%s is a palindrome\n", a);
return 0;

关于c - 如何在C中的回文代码中忽略符号和空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49102281/

相关文章:

c - 如何从高架摄像机考虑建筑物轨迹中像素的旋转?

c - 检测多个子进程的终止

c - 如何将结构转换为 D 中的 C 指针?

将 char 转换为整数导致段错误

c - 在C中,函数是在第一次调用时加载到内存中还是在程序启动时加载到内存中?它可以从内存中卸载吗?

c - strcmp 是线程安全的吗?

如果从 rand() 接收到值,则 C/Else 与 Else 中的投币程序

c - 用邻接矩阵实现无向图

c++ - #include <文件名> 和 #include "filename"有什么区别?

c - 使用结构体的成员作为验证