6.判断一个字符串(长度小于10)是否为回文字符串(指从左至右和从右至左读都是一样的字符串)。(某年期末考题)
【设计要求】
(1)使用字符数组char a[N]存储字符串。
(2)使用指针方式对字符数组进行访问,不能使用下标方式。
【输入输出样例1】
请输入长度小于10的字符串:abcdcba
Yes,abcdcba是回文字符串!
【输入输出样例2】
请输入长度小于10的字符串:abc
No,abc不是回文字符串!
程序代码:
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#define N 10
bool isPalindrome(char *s) {
int length = strlen(s);
char *start = s;
char *end = s + length - 1;
while (start < end) {
if (*start != *end) {
return false;
}
start++;
end--;
}
return true;
}
int main() {
char a[N];
printf("请输入长度小于10的字符串: ");
scanf("%s", a);
if (isPalindrome(a)){
printf("Yes, %s是回文字符串!\n", a);
} else {
printf("No, %s不是回文字符串!\n", a);
}
return 0;
}