C String Palindrome Check: Method & Code

One way to determine if a string is a palindrome is to gradually compare the first and last characters, moving towards the center until the two pointers meet or the left pointer is greater than the right pointer. If two characters are found to be unequal during the comparison process, then the string is not a palindrome. Below is a function written in C language to determine if a string is a palindrome:

#include <stdio.h>
#include <string.h>

int isPalindrome(char *str) {
    int len = strlen(str);
    int left = 0;
    int right = len - 1;

    while (left < right) {
        if (str[left] != str[right]) {
            return 0;
        }
        left++;
        right--;
    }

    return 1;
}

int main() {
    char str[100];
    printf("Enter a string: ");
    scanf("%s", str);

    if (isPalindrome(str)) {
        printf("The entered string is a palindrome.\n");
    } else {
        printf("The entered string is not a palindrome.\n");
    }

    return 0;
}

The isPalindrome function in the above code is used to determine if the input string is a palindrome. It first calculates the length of the string, then uses two pointers, left and right, to point to the beginning and end of the string. During the loop, if the characters pointed to by the two pointers are not equal, it returns 0, indicating that it is not a palindrome. If the two pointers meet or if the left pointer is greater than the right pointer, it returns 1, indicating that it is a palindrome.

bannerAds