C和指针之字符串编程练习10(判断字符串是否是回文数)

来源:互联网 发布:孙骁骁家庭知乎 编辑:程序博客网 时间:2024/06/05 17:10

1、问题

//如果参数字符串是个回文,函数就返回真,否则返回假。回文就是指一个字符串从左向右和从右向左读是一样的。函数应该忽略所有的非字母字符,而且在进行字符比较时不用区分大小写。







2、代码实现

#include <stdio.h>#include <ctype.h>//如果参数字符串是个回文,函数就返回真,否则返回假。回文就是指一个字符串从左向右和从右向左读是一样的。函数应该忽略所有的非字母字符,而且在进行字符比较时不用区分大小写。int palindrome(char *string){if (string == NULL)return 0;char *start  = string;char *end = string;//把end指向'\0',然后退以下,这里不要写成while (*end++ != '\0');//不然需要--end两次while (*end != '\0'){++end;}//尾巴指针退到字符串末尾--end;while (start < end){//这里不能用if,if只能移动一个非字符的下标,如果非字符是//连续的话,这里用if就会有问题while (!isalpha(*start))++start;while (!isalpha(*end))--end;//只要发现不相等,就返回0if (*start != *end)return 0;++start;--end;}    return 1;}int main(){     char *string_one = "w3e1rq778e89qr1e3w";char *string_two = "chenyu";char *string_three = "chenyuuynehc";char *string_four = "chen2323yu32323uy333nehc222222";printf("palindrome(%s) is %d\n", string_one, palindrome(string_one));printf("palindrome(%s) is %d\n", string_two, palindrome(string_two));printf("palindrome(%s) is %d\n", string_three, palindrome(string_three));printf("palindrome(%s) is %d\n", string_four, palindrome(string_four));return 0; }






3、运行结果

chenyu@chenyu:~/Desktop/linux/dabian/string$ vim palindrome.c chenyu@chenyu:~/Desktop/linux/dabian/string$ gcc -g palindrome.c -o palindromechenyu@chenyu:~/Desktop/linux/dabian/string$ ./palindrome palindrome(w3e1rq778e89qr1e3w) is 1palindrome(chenyu) is 0palindrome(chenyuuynehc) is 1palindrome(chen2323yu32323uy333nehc222222) is 1




原创粉丝点击