gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 14:50:11 25 4
gpt4 key购买 nike

#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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com