凯撒密码解密 - C++ 实现

凯撒密码是一种简单的替换加密方法,它将明文字母按照固定偏移量进行替换。本文将介绍凯撒密码解密的原理和实现方法,并提供一个用 C++ 编写的示例代码。

算法原理

凯撒密码解密需要将密文字母按照偏移量进行逆向替换,即如果偏移量为 k,则将每个密文字母向前移动 k 位。

C++ 实现

#include <iostream>
#include <string>

using namespace std;

string decryptCaesar(string encrypted, int offset) {
    string decrypted = "";
    for (int i = 0; i < encrypted.length(); i++) {
        if (isalpha(encrypted[i])) {
            char original = encrypted[i] - offset;
            if (original < 'A') {
                original += 26;
            }
            decrypted += original;
        } else {
            decrypted += encrypted[i];
        }
    }
    return decrypted;
}

int main() {
    string encrypted;
    int offset;
    cin >> encrypted >> offset;
    string decrypted = decryptCaesar(encrypted, offset);
    cout << decrypted << endl;
    return 0;
}

代码说明

  • decryptCaesar 函数接受两个参数:加密字符串和偏移量。
  • 函数遍历加密字符串,将每个字母进行逆向替换,并将结果存储在 decrypted 字符串中。
  • 如果字母小于 'A',则需要加上 26,以保证结果在字母表范围内。
  • main 函数读取输入的加密字符串和偏移量,调用 decryptCaesar 函数进行解密,并输出结果。

总结

本文介绍了凯撒密码解密的原理和 C++ 实现方法,并提供了完整的示例代码。该代码简单易懂,可以帮助您理解凯撒密码解密算法。


原文地址: https://www.cveoy.top/t/topic/oHcU 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录