文本加密

 

#include <iostream>
#include <string>
using namespace std;

string plain = "abcdefghijklmnopqrstuvwxyz";
string cipher = "ngzqtcomuhelkpdawxfyivrsj";

// 加密函数
string encrypt(string s) {
    string res;
    // 替换为C++98支持的下标遍历
    for (int i = 0; i < s.size(); i++) {
        char c = s[i];
        if (c >= 'a' && c <= 'z') {
            int idx = c - 'a';
            res += cipher[idx];
        } else {
            res += c;
        }
    }
    return res;
}

// 解密函数
string decrypt(string s) {
    string res;
    // 替换为C++98支持的下标遍历
    for (int i = 0; i < s.size(); i++) {
        char c = s[i];
        if (c >= 'a' && c <= 'z') {
            int idx = cipher.find(c); // 查找密文字符在cipher中的位置
            res += plain[idx];
        } else {
            res += c;
        }
    }
    return res;
}

int main() {
    string input;
    cout << "输入文本串:";
    getline(cin, input);
    
    string encrypted = encrypt(input);
    cout << "加密结果:" << encrypted << endl;
    
    string decrypted = decrypt(encrypted);
    cout << "解密结果:" << decrypted << endl;
    
    return 0;
}

 

posted @ 2025-11-05 13:35  ouyeye  阅读(6)  评论(0)    收藏  举报