如何在不知道对应关系的情况下在字符串中搜索字符并将其分配给另一个字符?

How to search a string for a char and assign it to another char without knowing the correspondence?

本文关键字:字符 另一个 搜索 分配 字符串 不知道 关系 情况下      更新时间:2023-10-16

第一个文件将正好包含两行,表示对文本进行编码的方法。第一行将是字母 A-Z 的子集,第二行上的字符将表示编码。第二个文件将是编码文本。

由于并非所有字母都出现在 file1 中,因此编码文本中可能存在您不知道如何解码的字母。这是使用第三个参数的地方。第三个参数将是已知出现在源文本中的单词。您的工作是尝试为密码中未知的部分分配相应的字母,直到第三个参数中的单词出现在解码的文本中。

文件 1:

ABCFGHIJKLMNPQRSTUVWXYZ PDFZATMEBYOCSWINVXLJRUQ (空行(

文件2:

VTK
GHA EXOSKG HLKI VTK ZKCFK (空行(

./p1 file1 file2 DOG

THE DOG JUMPED OVER THE FENCE

我的代码:

while(file2.get(c))
{  
if(ispunct(c) || isdigit(c) || isspace(c))
{
cout << c;
} 
if(word == "DOG")
{
if(c == 'K')
cout << "E";
}
if(word == "BACK")
{
if(c == 'A')
cout << "V";
}
for(int j = 0; j < str2.length(); j++)
{
if(c == str2.at(j))
{
cout << str1.at(j);
continue;
}
if(word.find(c) && (!(str2.find(c))))
{
if(c == str2.at(j))
continue;
for(int i = 0; i < word.size(); i++)
{
if(c != word.at(i))
{
???
break;
}
else
{
???
continue;
}
}
}
}          
}

这是一个代码片段,希望能帮助你理解算法。

std::string alphabet;
std::string encryption_key;
// Read in the alphabet string.
std::getline(std::cin, alphabet);
// Read in the encryption key.
std::getline(std::cin, encryption_key)
//...
std::string message;
while (std::getline(file2, message))
{
const unsigned int length = message.length();
for (unsigned int i = 0; i < length; ++i)
{
// Extract the character, for conversion, from the message.
const char c = message[i];
// Search the alphabet for the character.
// The alphabet contains the characters that are subject to conversion.
std::string::size_type position = alphabet.find(c);
if (position == std::string::npos)
{
// character is not in alphabet, print it and continue with next char.
std::cout << c;
continue;
}
else
{
// Lookup the character in the encryption key to get the index.
const unsigned int index = encryption_key.find(c);
// Convert the character, c, by using the same index into the alphabet.
const char converted = alphabet[index];
std::cout << converted;
}
}
}  

您需要处理字符在字母表中但不在加密密钥中的情况。

编辑:图表
此任务假定字母表和加密密钥之间存在 1:1 的关系。

+---+---+---+---+     +---+  
| A | B | C | D | ... | Z |  
+---+---+---+---+     +---+  
^   ^   ^   ^         ^  
|   |   |   |         |  
v   v   v   v         v  
+---+---+---+---+     +---+  
| P | D | F | Z | ... | Q |  
+---+---+---+---+     +---+  

对于解码,当你看到字母P时,你用字母A替换它,用B替换D,等等。