break-word; clear: both; text-indent: 2em; color: rgb(24, 30, 51); font-family: PingFangSC, 微软雅黑, 黑体, Arial, Helvetica, sans-serif; font-size: 18px; background-color: rgb(255, 255, 255); line-height: 2;">【案例描述】
break-word; clear: both; text-indent: 2em; color: rgb(24, 30, 51); font-family: PingFangSC, 微软雅黑, 黑体, Arial, Helvetica, sans-serif; font-size: 18px; background-color: rgb(255, 255, 255); line-height: 2;">编程实现:输入字符串(仅含数字或英文字母,不超过30个字符),输出加密后的字符串。加密方法为:
1、使用由10个数字和52个字母组成的密码本:0123456789AB...Zab..z
2、对字符的加密方法为:
(1)从密码本中找到该字符的位置k
(2)以密码本中第k+15个字符作为加密后的字符
规定:密码本中,z字符的后一个字符就是第一个字符
【案例分析】
求解的基本思路是:
1、用一个数组存储密码本:
char pwd[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
2、用2个数组,1个存储输入的字符串,1个存储加密后的字符串:
char s[31],t[31];
3、对输入的字符串逐字符加密:如果字符在密码本中的位置为k,则其加密后的字符串为pwd[(k+15)%62]
【参考代码】
main()
{ char pwd[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
char s[31],t[31],k,i=0;
scanf("%s",s);
while(s[i]) //对字符串的第i个字符加密(i的初值为0)
{ for(k=0;k<62;k++) //在密码本中查找字符s[i]的位置
if(s[i]==pwd[k])break;
k=(k+15)%62; //得到字符s[i]加密后的字符位置
t[i++]=pwd[k];//得到字符s[i]加密后的字符
}
t[i]=0; //加密完成。字符串必须以ASCII码值为0的字符结尾
printf("%s",t); //输出加密后的字符串
}
【思考】