判断回文:判断输入的一串字符是否为“回文”。所谓“回文”是指顺读和倒读都一样的字符串。如“XYZYX"和“xyzzyx"都是回文。试编写相应程序。
#include<stdio.h>
int main(void){
char ca[20];
int i,j,n; //i、j分别控制数组从前、从后遍历;n记录字符串长度
printf("input a string: ");
gets(ca);
n=0;
while(ca[n] != '\0'){ //统计字符长度,从而方便在字符的两端向中间靠拢
n++;
}
for(i=0,j=n-1; i<n&&i<=j; i++,j--){ //从两端向中间靠拢,当对称位置的字符不相等,则非回文
if(ca[i] != ca[j])
break;
}
if(i>=j) //for循环正常结束,则为对称字符串,即回文
printf("yes\n");
else //for提前结束,有不对称的地方,非回文
printf("no\n");
return 0;
}
#include <stdio.h> void main() { char s[80]; int mirror(char *p); gets(s); if(mirror(s) != 0) printf("YES\n"); else printf("NO\n"); } int mirror(char *p) { char *q; q = p; while(*q != '\0') q++; q--; while(p < q){ if(*p != *q) return 0; p++; q--; } return 1; }