题解 | #字符串加密#
字符串加密
http://www.nowcoder.com/practice/e4af1fe682b54459b2a211df91a91cf3
#include<stdio.h>
int main() {
char key[101] = { '0' };
char sec[101] = { '0' };
while (scanf("%s\n%s", &key, &sec) != EOF)
{
int len = strlen(key); //密钥长度
int seclen = strlen(sec); //密码长度
int num[26] = { 0 }; //原26字母出现标志组-出现则标1
char newkey[26] = { '0' }; //加密字母表
int m = 0; //加密字母表序号
int index = 0; //字母转换值(-'A')
char newsec[101] = { '0' }; //加密后字符串
//1.密钥全部转为大写
for (int i = 0; i < len; i++)
{
key[i] = toupper(key[i]);
}
//2.密钥有该字母则标记为1,并按序存入加密字母表,不重复存
for (int i = 0; i < len; i++)
{
index = key[i] - 'A'; //字母序号
if (num[index] == 0) {
num[index] = 1; //该字母出现则表内置1
newkey[m++] = key[i]; //按序存入加密字母表中
}
}
//3.存剩余未出现的字母入加密字母表中
for (int i = 0; i < 26; i++)
{
if (num[i] != 1) {
newkey[m++] = i + 'A';
}
}
//4.字符串加密
for (int i = 0; i < seclen+1; i++)
{
if (sec[i] >= 'A' && sec[i] <= 'Z')
{
index = sec[i] - 'A';
newsec[i] = toupper(newkey[index]);
}
else if (sec[i] >= 'a' && sec[i] <= 'z')
{
index = sec[i] - 'a';
newsec[i] = tolower(newkey[index]);
}
}
for (int i = 0; i < seclen; i++)
{
printf("%c", newsec[i]);
}
printf("\n");
}
return 0;
}