编写函数intpalindrome(char *str);
如果参数字符串是个回文,函数就返回真,否则就返回假。回文就是指一个字符串从左向右读和从右向左读是一样的。函数应该忽略所有的非字母字符,而且在进行字符比较时不用区分大小写。
《C和指针》第九章9.10题
#include <ctype.h> #include <string.h> int palindrome(char *str) { char *end; end = str + strlen(str)-1; while (str != NULL) { //如果遇到非字母字符,指针前移或后移 while (isalpha(*str) == 0) { str++; } while (isalpha(*end) == 0) { end--; } //如果前指针超过了尾指针,是回文 if (end <= str) { return 1; } //比较前后每一个字母字符(转化为小写字母比较),如果不一样则不是回文 if (tolower(*str) != tolower(*end)) { return 0; } //如果一样,则移动指针到下一个字符 str++; end--; } return 0; }