Check if a string is a palindrome in C programming language.
To determine if a string is a palindrome, follow these steps:
- Define two pointers, one pointing to the beginning of the string and one pointing to the end of the string.
- For each pair of pointers pointing to characters, compare if they are equal. If they are, move both pointers towards the center by one position; if they are not, then the string is not a palindrome.
- Repeat step 2 until the two pointers meet or cross each other.
- If the two pointers meet, it means the string is a palindrome; if the two pointers cross, it means the string is not a palindrome.
Here is an example code:
#include <stdio.h>
#include <string.h>
int isPalindrome(char* str) {
int start = 0;
int end = strlen(str) - 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("%s 是回文串\n", str);
} else {
printf("%s 不是回文串\n", str);
}
return 0;
}
The above code determines if a string is a palindrome by comparing its first and last characters. During the comparison, if any unequal characters are found, it can immediately return 0, indicating it is not a palindrome. The final result is output based on the return value of the function.