Check Palindrome in C: Two-Pointer Method

To determine if a string is a palindrome, you can follow these steps:

  1. Define two pointers, one pointing to the beginning and the other to the end of the string;
  2. Continuously compare if the characters pointed to by two pointers are equal, if they are, continue moving towards the center until the two pointers meet.
  3. If during the comparison process, it is found that the characters pointed to by the two pointers are not equal, then the string is not a palindrome.
  4. If the two pointers meet without finding any unequal characters, then the string is a palindrome.

Here is an example code implemented in C language:

#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;
}

Once a string is inputted, the program will determine if it is a palindrome and output the result.

bannerAds