Atbash 密码程序 A = Z, B = Y, C = X

Atbash Cipher Program A = Z, B = Y, C = X

本文关键字:密码 程序 Atbash      更新时间:2023-10-16

>我正在尝试创建一个将生成Atbash密码的程序。基于此代码,如何反转每个字母?比如 A = Z、B = Y、C = X?

 #include<iostream>
#include<stdio.h>
#include<string>
using namespace std;
string encrypt(string str);
int main(){
    string text = "", result = "";
    cout << "Enter text to encrypt: ";getline(cin, text);
    result = encrypt(text);
    cout << "Encrypted text: " << result;
}
string encrypt(string str) {
    string temp = str;
    string sample;
    char alphabeta[13] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm'};
    char alphabetb[13] = {'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
    char Ualphabeta[13];
    char Ualphabetb[13];
    for(int i = 0;i < 13;i++){
        Ualphabeta[i] = toupper(alphabeta[i]);
    }
    for(int i = 0;i < 13;i++){
        Ualphabetb[i] = toupper(alphabetb[i]);
    }
    cout << endl;
    return temp;
}
 

不需要查找数组,因为您可以简单地计算与字母表末尾的距离,然后从中计算出来。看:

#include <iostream>
#include <string>
#include <cctype>
int main()
{
  const int letterCount = 'z' - 'a' + 1 ;
  std::string name = "Hello world!";
  for(auto& letter: name){
      if(!std::isalpha(letter)) { 
        continue;
      }
      const bool isUpper = std::isupper(letter);
      const char baseOffset = isUpper? 'A': 'a';
      const auto distanceFromAlphabetStart = letter - baseOffset;
      letter = (baseOffset + letterCount - 1) - distanceFromAlphabetStart;
      // substract the initial position from z (either uppercase or lowercase).
  }
  std::cout << name;
}

https://repl.it/repls/ThornyPowerfulHexadecimal