题解 | #字符串加密#
字符串加密
https://www.nowcoder.com/practice/e4af1fe682b54459b2a211df91a91cf3
#include <stdio.h> #include <string.h> int main(){ char key[99], text[102]; scanf("%s", key); getchar(); //消除换行符 fgets(text, sizeof(text), stdin); text[strlen(text) - 1] = '\0'; int len_key = strlen(key); char buf[26]; int mark[26] = {0}; //标记数组 int k = 0; //buf数组的下标 for(int i = 0; i < len_key; i++){ if(mark[key[i] - 'a'] == 0){ //如果该字母没有出现过 mark[key[i] - 'a'] = 1; //标记为已出现 buf[k++] = key[i]; //存入buf数组 } } int len_buf = k; //buf数组的长度等于k for(int i = 'a'; i <= 'z'; i++){ if(mark[i - 'a'] == 0){ //如果该字母没有出现过 mark[i - 'a'] = 1; //标记为已出现 buf[k++] = i; //存入buf数组 } } //不需要定义dics数组,直接用buf数组作为加密映射表 int len_text = strlen(text); char paswd[102]; for(int i = 0; i < len_text; i++){ if(text[i] >= 'a' && text[i]<= 'z'){ paswd[i] = buf[text[i] - 'a']; //用buf数组替换明文中的字母 } else{ paswd[i] = text[i]; } } paswd[len_text] = '\0'; //添加结束符 printf("%s", paswd); return 0; }