如何检测C中的回文?

Wal*_*rop 5 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");
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

Ale*_*lli 5

将循环更改为

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

  • +1而不是'ispunct(x)|| isspace(x)`我可能会使用`!isalpha(x)`.它略有不同,但在我看来,它在眼睛上更容易一些. (3认同)
  • 这将完全由标点符号(以及其他)组成的字符串失败.你需要在这些循环中进行更多检查,以确保在跳过标点符号时,`end`和`begin`不会相互通过. (3认同)