如何在不知道对应关系的情况下在字符串中搜索字符并将其分配给另一个字符?
How to search a string for a char and assign it to another char without knowing the correspondence?
第一个文件将正好包含两行,表示对文本进行编码的方法。第一行将是字母 A-Z 的子集,第二行上的字符将表示编码。第二个文件将是编码文本。
由于并非所有字母都出现在 file1 中,因此编码文本中可能存在您不知道如何解码的字母。这是使用第三个参数的地方。第三个参数将是已知出现在源文本中的单词。您的工作是尝试为密码中未知的部分分配相应的字母,直到第三个参数中的单词出现在解码的文本中。
文件 1:
ABCFGHIJKLMNPQRSTUVWXYZ PDFZATMEBYOCSWINVXLJRUQ (空行(文件2:
VTKGHA 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
,等等。
相关文章:
- 使用.find函数在c++中查找字符和另一个字符之间的大小
- 关于字符数组,我正在尝试将数组中的每个字符分配给另一个值
- 使用动态分配将 char* 复制到另一个字符**
- 将字符向量复制到另一个向量
- 如何将一个结构的字符数组复制到结构的另一个字符数组中?
- 如何在不知道对应关系的情况下在字符串中搜索字符并将其分配给另一个字符?
- 如何检查一个字符是否与字符数组中的另一个字符匹配?
- C++:使用另一个字符将一个字符大写
- 将字符从一个字符串简单分配到另一个字符串不起作用
- 使用 char 将一个字符数组分配给另一个字符数组时出现奇怪的行为
- 字符* 复制到另一个字符* 运行时错误
- 使用另一个字符数组进行字符初始化
- 将字符指针传递给另一个函数
- 在另一个字符串中逐个复制字符串字符
- C :在字符串中找到一个char,然后在先前的char之后找到另一个字符
- 炭的类型乘以另一个字符
- 如何在 C++ 的字符串中打印从一个索引到另一个索引的字符范围
- 字符串构造函数将两个字符* 放入另一个 std::string 在 C++14 中有效,但不适用于 C++17
- 计算一个字符串的每个字符在另一个字符串中的出现次数
- 给定一个字符串,如何检查前几个字符 == 另一个字符串?C++