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

时间:2019-04-24 17:01:30

标签: c++

我正在尝试创建一个将生成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; }

1 个答案:

答案 0 :(得分:1)

不需要查找数组,因为您可以简单地计算到字母末尾的距离,然后进行计算。 参见:

#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