Check whether a string is a palindrome in the C language.
A palindrome string is one that reads the same from left to right as it does from right to left. By using two pointers, one pointing to the beginning of the string and the other to the end, you can compare the characters they point to. If they are not the same, it is not a palindrome. If they are the same, the pointers move towards the middle to continue comparing. When the two pointers meet, it means the entire string has been compared without any mismatched characters, thus confirming it is a palindrome.
Here is a code in C language that checks if a given string is a palindrome.
#include <stdio.h>
#include <string.h>
int isPalindrome(char str[]) {
int length = strlen(str);
int i, j;
for (i = 0, j = length - 1; i < j; i++, j--) {
if (str[i] != str[j]) {
return 0; // 不是回文字符串
}
}
return 1; // 是回文字符串
}
int main() {
char str[100];
printf("请输入一个字符串:");
scanf("%s", str);
if (isPalindrome(str)) {
printf("%s 是回文字符串\n", str);
} else {
printf("%s 不是回文字符串\n", str);
}
return 0;
}
Example input:
请输入一个字符串:level
Output example:
level 是回文字符串
Input example:
请输入一个字符串:hello
Output example:
hello 不是回文字符串