本题要求编写程序,将给定字符串中的大写英文字母按以下对应规则替换:
原字母 | 对应字母 |
---|---|
A | Z |
B | Y |
C | X |
D | W |
… | … |
X | C |
Y | B |
Z | A |
输入在一行中给出一个不超过80个字符、并以回车结束的字符串。
输出在一行中给出替换完成后的字符串。
Only the 11 CAPItaL LeTtERS are replaced.
Lnly the 11 XZKRtaO OeGtVIH are replaced.
方法一:
- #include "stdio.h"
- #include "string.h"
- int main(){
- char str1[81];
- //定义交换目录
- char changeArray[26][2] = {
- {'A','Z'}, {'B','Y'},
- {'C','X'}, {'D','W'},
- {'E','V'}, {'F','U'},
- {'G','T'}, {'H','S'},
- {'I','R'}, {'J','Q'},
- {'K','P'}, {'L','O'},
- {'M','N'}, {'N','M'},
- {'O','L'}, {'P','K'},
- {'Q','J'}, {'R','I'},
- {'S','H'}, {'T','G'},
- {'U','F'}, {'V','E'},
- {'W','D'}, {'X','C'},
- {'Y','B'}, {'Z','A'}
- };
- char str2[81];
- //输入str1
- fgets(str1,sizeof(str1),stdin);
- for (int i = 0; i < strlen(str1); ++i) {
- int flag = 0;
- for (int j = 0; j < 26; ++j) {
- //如果为大写字母
- if (str1[i] == changeArray[j][0]){
- str2[i] = changeArray[j][1];
- flag = 1;
- break;
- }
- }
- //如果为非小写
- if (flag == 0)
- str2[i] = str1[i];
- }
- printf("%s",str2);
- return 0;
- }
方法二:
- #include "stdio.h"
- #include <string>
- int main(){
- char str[81];
- fgets(str,sizeof(str),stdin);
- for (int i = 0; i < 81; ++i) {
- //如果为大写
- if (isupper(str[i])){
- //重写str元素的值
- str[i] = 'Z' - (str[i] - 'A');
- }
- }
- printf("%s",str);
- return 0;
- }
以上代码全为本人亲自手敲,可能有一些错误和不足之处,如有更好的方法和建议,欢迎您在评论区友善讨论。