check if a string is a palindrome in C
Code snippet on how to check if a string is a palindrome in C
int isPalindrome(char str[])
{
// Start from leftmost and rightmost corners of str
int l = 0;
int h = strlen(str) - 1;
// Keep comparing characters while they are same
while (h > l)
{
if (str[l++] != str[h--])
return 0;
}
return 1;
}
This code checks if a given string is a palindrome or not. It takes the string as a parameter and returns 0 or 1 depending on the result. The first step is to define two variables, l for the leftmost corner of the string and h for the rightmost corner. The loop then runs which keeps comparing the characters of the string starting from the leftmost corner until the rightmost corner. If a mismatched character is found, it returns 0 which implies the string is not a palindrome. If no mismatched characters are found, it returns 1 meaning the string is a palindrome.