c - 我如何检测C中的回文?

标签 c

我一直在研究潜在的面试问题,其中之一是用 C 编写一个函数来检测给定的字符串是否为回文。

我已经有了一个很好的开始:

#include <stdio.h>
#include <stdbool.h>

bool isPalindrome(char *value);

bool isPalindrome(char *value)
{
    if (value == null)
        return false;

    char *begin = value;
    char *end = begin + strlen(value) - 1;

    while(*begin == *end)
    {
        if ((begin == end) || (begin+1 == end))
            return true;

        begin++;
        end--;
    }

    return false;
}


int main()
{
    printf("Enter a string: \n");
    char text[25];
    scanf("%s", text);

    if (isPalindrome(text))
    {
        printf("That is a palindrome!\n");
    }
    else
    {
        printf("That is not a palindrome!\n");
    }
}

但是,我现在想确保忽略空格和标点符号。

考虑到我上面编写的代码,如果指针遇到标点符号/空格,向前或向后移动指针的最佳方法是什么?

最佳答案

将循环更改为

while(begin < end) {
  while(ispunct(*begin) || isspace(*begin))
    ++begin;
  while(ispunct(*end) || isspace(*end))
    --end;
  if(*begin != *end)
    return false;
  ++begin;
  --end;
}
return true;

关于c - 我如何检测C中的回文?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2353955/

相关文章:

c - 在 execvp 之前设置 gid,但 id 命令显示多个组

c - %02x 字符数组的格式说明符

C(非C++)传值/引用面试题

c - C语言中的悬空指针

c - 在 C 中将二维数组引用到函数和逗号分隔语句的其他最佳或更好的方法

c - 为什么这里不发生整数除法截断?

C:在单独的函数中操作结构

将 OpenOffice/Libreoffice 与代码文档的 Doxygen 结果结合起来?

c - 如何获取内部结构的大小

c - 在数组上使用自由函数 (C) 时我的程序崩溃