版权声明:转自可爱的安安的博客!qq:1085589289 https://blog.csdn.net/ac1085589289/article/details/83824781
加粗样式# 题目
输入一个字符串,判断它是否为回文串以及镜像串。输入字符串保证不含数字0。所谓回文串,就是反转以后和原串相同,如abba和madam。所有镜像串,就是左右镜像之后和原串相同,如2S和3AIAE。注意,并不是每个字符在镜像之后都能得到一个合法字符。在本题中,每个字符的镜像如图所示(空白项表示该字符镜像后不能得到一个合法字符)。
输入的每行包含一个字符串(保证只有上述字符。不含空白字符),判断它是否为回文串和镜像串(共4种组合)。每组数据之后输出一个空行。
样例输入:
NOTAPALINDROME
ISAPALINILAPASI
2A3MEAS
ATOYOTA
样例输出:
NOTAPALINDROME – is not a palindrome.
ISAPALINILAPASI – is a regular palindrome.
2A3MEAS – is a mirrored string.
ATOYOTA – is a mirrored palindrome.
分析
- 使用常量数组,只用少量代码即可解决这个看上去有些复杂的题目
程序
#include<stdio.h>
#include<string.h>
#include<ctype.h>
const char* rev="A 3 HIL JM 0 2TUVWXY51SE Z 8 ";
const char* msg[]={"not a plindrom","a regular palindrome",
"a mirrored string","a mirrored palindrome"};
//自定义函数,ch是一个字符,返回值是ch的镜像字符。
char r(char ch)
{
if(isalphach(ch)) return rev[ch-'A'];
return rev[ch-'0'+25];
}
int main()
{
char s[30];
while(scanf("%s",s)==1)
{
int len=strlens(s);
int p=1,m=1;
for(int i=0;i<(len+1)/2;i++)
{
if(s[i]!=s[len-1-i]) p=0;
if(r(s[i])!=s[len-1-i]) m=0;
}
printf("%s--is %s.\n\n",s,msg[m*2+p]);
}
return 0;
}
编程提示
- 本题用isalpha来判断字符是否为字母,类似的还有C 库函数 void isdigit(int c) 检查所传的字符是否是十进制数字字符。(十进制数字是:0 1 2 3 4 5 6 7 8 9 )C 库函数 int isprint(int c) 检查所传的字符是否是可打印的。可打印字符是非控制字符的字符。
- 头文件:#include <ctype.h>
定义函数:int toupper(int c);
函数说明:若参数 c 为小写字母则将该对应的大写字母返回。
返回值:返回转换后的大写字母,若不须转换则将参数c 值返回。
#include <ctype.h>
#include<stdio.h>
main(){
char s[] = "aBcDeFgH12345;!#$";
int i;
printf("before toupper() : %s\n", s);
for(i = 0; i < sizeof(s); i++)
s[i] = toupper(s[i]);
printf("after toupper() : %s\n", s);
}
- 头文件:#include <stdlib.h>
定义函数:int tolower(int c);
函数说明:若参数 c 为大写字母则将该对应的小写字母返回。
返回值:返回转换后的小写字母,若不须转换则将参数c 值返回。
范例:将s 字符串内的大写字母转换成小写字母。
#include <ctype.h>
#include<stdio.h>
main(){
char s[] = "aBcDeFgH12345;!#$";
int i;
printf("before tolower() : %s\n", s);
for(i = 0; i < sizeof(s); i++)
s[i] = tolower(s[i]);
printf("after tolower() : %s\n", s);
}
- 如果ch是大写字母,则ch-'A’就是他在字母表中的序号;类似地,如果ch是数字,则ch-'0’就是这个数字的数值本身。
总结
越学习越觉得自己自己之前写的代码傻逼!!!