[英]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.