温馨提示×

实现一个回文检测器:C语言实践案例

小樊
82
2024-04-26 17:15:52
栏目: 编程语言

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

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

    while (left < right) {
        while (!isalnum(str[left]) && left < right) {
            left++;
        }
        while (!isalnum(str[right]) && left < right) {
            right--;
        }

        if (tolower(str[left]) != tolower(str[right])) {
            return 0;
        }

        left++;
        right--;
    }

    return 1;
}

int main() {
    char str[100];
    
    printf("Enter a string: ");
    fgets(str, sizeof(str), stdin);

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

    return 0;
}

这个程序实现了一个回文检测器,用户可以输入一个字符串,程序将检测这个字符串是否为回文。程序会忽略字符串中的非字母字符,并且不区分大小写。如果字符串是回文,则程序会输出"The string is a palindrome.“,否则输出"The string is not a palindrome.”。

0