C语言实例解析精粹学习笔记——31

实例31:

  判断字符串是否是回文

思路解析:

  引入两个指针变量(head和tail),开始时,两指针分别指向字符串的首末字符,当两指针所指字符相等时,两指针分别向后和向前移动一个字符位置,并继续比较,直至两指针相遇,说明该字符串是回文。若比较过程中,发现两字符不相等,则可以判断该字符串不是回文。

程序如下:

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include <string.h>
 4 
 5 #define MAX 50
 6 
 7 int cycle(char *s)
 8 {
 9     char *head, *tail;
10 
11     for(head=s,tail=s+strlen(s)-1; tail>head; head++,tail--)
12     {
13         if(*head != *tail)
14             break;
15     }
16     return tail <= head;
17 }
18 
19 int main()
20 {
21     char s[MAX];
22 
23     while(1)
24     {
25         puts("Please input the string you want to judge (input ^ to quit):");
26         scanf("%s",s);
27         if(s[0] == '^')
28             break;
29         if(cycle(s))
30             printf("%s is a cycle string.
",s);
31         else
32             printf("%s is not a cycle string.
",s);
33     }
34 
35     printf("
Thank you for your using, bye bye !
");
36     return 0;
37 }

  第16行的代码在练习过程中写成了tail<head,会出现错误。对于字符串“aba”会显示not a cycle string.

原文地址:https://www.cnblogs.com/llccbb1/p/9744991.html