[英]Simple encryption with encryption key
我正在做简单的加密。 我有一个叫做加密的功能(字符串文本,字符串encryption_key)。 它应该用encryption_key的第一个字母替换文本的a,用第二个字母替换b,以此类推。 我正在尝试使用ASCII值解决此问题。
我不确定我是否认为这是正确的,但是我已经尝试过类似的方法:
void encryption(std::string text, std::string encryption_key){
for(long unsigned int i=0; i< encryption_key.length();i++){
char letter = encryption_key.at(i);
for(char j = 'a'; j<='z'; j++){
if(text.find(j) != std::string::npos){
text.at(j)= letter;
}
}
std::cout<<"Encrypted text: "<< text<<std::endl;
}
}
我在抛出“ std :: out_of_range”的what()实例后得到“终止调用”:basic_string :: at:__n(101)> = this-> size()(5)按下以关闭此窗口......”
我尝试先通过加密密钥字符并替换文本中的字符(az)的想法正确吗?
固定:
auto pos = text.find(j);
if(pos != std::string::npos) {
text[pos] = letter;
}
您的代码的解决方法是text.at(text.find(j)) = letter;
void encryption(std::string text, std::string encryption_key){
for(long unsigned int i=0; i< encryption_key.length();i++){
char letter = encryption_key.at(i);
for(char j = 'a'; j<='z'; j++){
if(text.find(j) != std::string::npos){
text.at(text.find(j))= letter;
}
}
std::cout<<"Encrypted text: "<< text<<std::endl;
}
}
但我相信,根据您的描述,该算法是错误的。
编辑:不使用库,您可以执行以下操作:
void encryption(std::string text, std::string encryption_key)
{
for (int i=0; i<text.length(); i++)
{
for (char ch = 'a'; ch<='z'; ch++)
{
if (text[i] == ch)
{
text[i] = encryption_key[ch-'a'];
break;
}
}
}
std::cout<<"Encrypted text: "<< text<<std::endl;
}
使用replace
算法,您可以轻松地做到这一点。 它将遍历text
字符串,并将所有出现的特定字母替换为encryption_key
的相应值。 在这里, encryption_key
包含所有小写字母的加密值。
void encryption(std::string text, std::string encryption_key){
int j = 0;
for(auto i = 'a'; i <= 'z'; i++) //text has only small letters
{
std::replace( text.begin(), text.end(), i, encryption_key.at(j));
j++;
}
std::cout <<"Encrypted text: "<< text<<std::endl;
}
见DEMO
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.