You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于字母频率替换的C++文本解密代码实现求助

基于字母频率法实现通用文本解密的C++方案

需求说明

我正在完成作业任务,需要用字母频率法解密加密文本,具体要求:

  • 读取encrypted.txt中的加密内容
  • 统计每个字符的出现频率
  • 对照英语字母频率表,按频率从高到低对应替换字符(示例中AAAAAA BB RRRR L替换为EEEEEE AA TTTT O,高频加密字符对应高频英文字母)
  • 将解密结果输出到decrypted.txt

目前已实现字符统计与频率排序,但无法动态建立「加密字符-目标字符」的对应关系,当前代码为硬编码替换,无法适配不同的加密文本,需实现通用替换逻辑。

现有硬编码代码

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

int main() {
  string str;
  int most1,most2,most3,most4;///Thinking of using these to find out which letter it is 
  int n=4;///How many letters there are(for sorting)
  int Array[3];///An array where I put the count of all letters and then sort it
  int Ax=0, Bx=0, Lx=0, Rx=0;///With these I store the sum of each letter (how many times they repeat themselves)

  ifstream read("encrypted.txt");
  ofstream write("decrypted.txt");
  while (getline(read,str)) {
    for(char &ch:str) {
        if(ch=='A'){
          Ax++;///If a specific letter is found, I count it
          Array[0]=Ax;///Transferring the count of letters found to the array
        }
        if(ch=='B'){
          Bx++;///If a specific letter is found, I count it
          Array[1]=Bx;///Transferring the count of letters found to the array
        }
        if(ch=='L'){
          Lx++;///If a specific letter is found, I count it
          Array[2]=Lx;///Transferring the count of letters found to the array
        }
        if(ch=='R'){
          Rx++;///If a specific letter is found, I count it
          Array[3]=Rx;///Transferring the count of letters found to the array
        }
        }
      }

  sort(Array, Array+n, greater<int>());///Sorting the Array in a descending order

most1=Array[0];/// value in here is 6
most2=Array[1];/// value in here is 4
most3=Array[2];/// value in here is 2
most4=Array[3];/// value in here is 1

 ///Here I read the file again in order to replace the letters with the corresponding ones
read.close();
read.clear();
read.seekg(0, read.beg);
read.open("encrypted.txt");

  while (getline(read,str)) {
    for(char &ch:str) {
      if(ch=='A'){///How do you read a letter and check how many times it repeats itself and then determine which letter it has to be depending on the amount of times it repeated itself.
       ch='E';
      }
      if(ch=='R'){
       ch='T';
      }
      if(ch=='B'){
       ch='A';
      }
      if(ch=='A'){
       ch='L';
      }
    }
    write<<str<<endl;
  }

  read.close();
  write.close();
  return 0;
}

通用解决方案代码

#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
#include <vector>
#include <unordered_map>
#include <cctype>

using namespace std;

// 英语字母频率从高到低的参考顺序(可根据需求调整)
const string ENGLISH_FREQ = "ETAOINSHRDLCUMWFGYPBVKJXQZ";

int main() {
    // 1. 统计所有字母的出现频率
    unordered_map<char, int> charCount;
    ifstream read("encrypted.txt");
    string str;

    if (!read.is_open()) {
        cerr << "无法打开encrypted.txt文件" << endl;
        return 1;
    }

    while (getline(read, str)) {
        for (char ch : str) {
            // 仅统计字母,忽略空格等非字母字符
            if (isalpha(ch)) {
                charCount[toupper(ch)]++; // 统一转为大写统计,避免大小写干扰
            }
        }
    }
    read.close();

    // 2. 将字符按出现频率从高到低排序
    vector<pair<char, int>> sortedChars(charCount.begin(), charCount.end());
    sort(sortedChars.begin(), sortedChars.end(),
         [](const pair<char, int>& a, const pair<char, int>& b) {
             return a.second > b.second;
         });

    // 3. 建立加密字符到目标字符的映射表
    unordered_map<char, char> replaceMap;
    for (size_t i = 0; i < sortedChars.size() && i < ENGLISH_FREQ.size(); ++i) {
        // 大写映射
        replaceMap[sortedChars[i].first] = ENGLISH_FREQ[i];
        // 同步建立小写映射,保持原文本大小写格式
        replaceMap[tolower(sortedChars[i].first)] = tolower(ENGLISH_FREQ[i]);
    }

    // 4. 读取原文件并替换字符,输出解密结果
    ofstream write("decrypted.txt");
    if (!write.is_open()) {
        cerr << "无法创建decrypted.txt文件" << endl;
        return 1;
    }

    read.open("encrypted.txt");
    while (getline(read, str)) {
        for (char& ch : str) {
            // 仅替换字母字符,其他字符保持不变
            if (isalpha(ch) && replaceMap.count(ch)) {
                ch = replaceMap[ch];
            }
        }
        write << str << endl;
    }

    read.close();
    write.close();
    return 0;
}

关键改进说明

  • 通用统计:用unordered_map自动统计所有字母的出现次数,无需硬编码指定字符,适配任意加密文本
  • 动态映射:将排序后的加密字符依次对应到英语高频字母表,自动生成替换规则,无需手动指定
  • 大小写兼容:统一大写统计,同时建立大小写映射,保留原文本的大小写格式
  • 错误处理:增加文件打开失败的判断,避免程序崩溃

内容的提问来源于stack exchange,提问作者user20832627

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 13:35:15