Determining if a string is a palindrome in the C language
One way to determine if a string is a palindrome is to use the concept of using two pointers. One pointer points to the beginning of the string and the other pointer points to the end of the string. Then, gradually compare whether the characters pointed to by the two pointers are the same until the two pointers meet or a different character is found.
Here is an example code:
#include <stdio.h>
#include <string.h>
int isPalindrome(char* str) {
int len = strlen(str);
int start = 0;
int end = len - 1;
while (start < end) {
if (str[start] != str[end]) {
return 0; // 不是回文
}
start++;
end--;
}
return 1; // 是回文
}
int main() {
char str[100];
printf("请输入一个字符串:");
scanf("%s", str);
if (isPalindrome(str)) {
printf("是回文\n");
} else {
printf("不是回文\n");
}
return 0;
}
This code first obtains the length of the string using the strlen function, and then uses two pointers, start and end, to point to the beginning and end of the string respectively. Within a while loop, it continuously compares if the characters pointed to by the two pointers are the same. If different characters are found, it returns 0 indicating it is not a palindrome; if the two pointers meet, it indicates that the entire string has been compared and returns 1 indicating it is a palindrome. Finally, in the main function, the isPalindrome function is called for evaluation and the result is output.