#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;
}
}
}
这适用于像“女士”这样没有任何符号的字符串。有没有办法忽略所有符号,如“。”,“”,“'”,实际上,所有非字母数字字符。有没有办法使这项工作?
您可以使用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;
isalnum检查将检查字符是否为字母数字。在比较之前,tolower将小写字符。我为角落案例添加了这些检查和一些逻辑。看看这是否有效。它适用于我的Mac。
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main(int argc, char **argv) {
int l = 0;
char a[] = "Madam, I'm Adam.";
int h = strlen(a) - 1;
int match = 0;
while (h > 1 && l <= h) {
if (!isalnum (a[h])) {
h--;
continue;
}
if (!isalnum (a[l])) {
l++;
continue;
}
if (tolower(a[l++]) != tolower(a[h--])) {
printf("%s is not a palindrome\n", a);
return 1;
}
match = 1; /* at least one alphanum haracter match */
}
if (match == 1) {
/* We need at least one true alphanum character match */
printf("%s is a palindrome\n", a);
return 0;
}
else
{
printf ("String of special chars %s \n", a);
return 1;
}
}