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

   2024-10-20 2940
核心提示:#include stdio.h#include string.h#include ctype.hint isPalindrome(char *str) {int left = 0;int right = strlen(str) - 1;w

#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.”。

 
举报打赏
 
更多>同类网点查询
推荐图文
推荐网点查询
点击排行

网站首页  |  关于我们  |  联系方式网站留言    |  赣ICP备2021007278号