凯撒密码解密 - C++ 实现
凯撒密码解密 - C++ 实现
凯撒密码是一种简单的替换密码,它通过将每个字母替换为字母表中后移固定位置的字母来加密。例如,将每个字母向后移 5 个位置,则字母 A 将被替换为 F,B 将被替换为 G,以此类推。
解密算法
解密凯撒密码需要将密文中的每个字母向前移固定位置。例如,如果加密时每个字母向后移 5 个位置,则解密时需要将每个字母向前移 5 个位置。
C++ 代码实现
#include <iostream>
#include <string>
using namespace std;
string decrypt(string ciphertext) {
string plaintext = '';
for (int i = 0; i < ciphertext.length(); i++) {
char c = ciphertext[i];
if (c >= 'A' && c <= 'Z') {
int index = c - 'A';
index = (index + 21) % 26;
plaintext += 'A' + index;
}
}
return plaintext;
}
int main() {
string ciphertext;
getline(cin, ciphertext);
string plaintext = decrypt(ciphertext);
cout << plaintext << endl;
return 0;
}
代码解析
decrypt(string ciphertext)函数接收一个字符串参数ciphertext,表示密文。- 在循环中遍历每个字符
c。 - 如果
c是大写字母,则计算其在字母表中的位置index。 - 将
index向前移 21 个位置,即(index + 21) % 26,并将其转换为对应的字母。 - 将解密后的字母添加到
plaintext字符串中。 main()函数接收用户输入的密文,并调用decrypt()函数解密密文,最后输出解密后的明文。
总结
本文介绍了如何使用 C++ 代码实现凯撒密码的解密,并提供了一个示例程序。该程序可以解密任何以字母表后移固定位置的方式加密的密文。
原文地址: https://www.cveoy.top/t/topic/qtF4 著作权归作者所有。请勿转载和采集!