替换两个不同数组之间的字符
Replace characters between two different arrays C++
我有两个字母表数组,它们以两种不同的方式按我需要的顺序排序。现在我需要按照顺序,将索引b[]中的第一个字母替换为索引a[]中的第一个字母,一直到它们的第26个字母。我使用replace()函数来更改文本中需要交换字母的字母,然后用所有交换输出消息。但是代码没有调换我想要调换的字母。任何建议吗?
char c;
vector<char> fileChars;
while (code.good())
{
code.get(c);
fileChars.push_back(c);
}
for (int i = 0; i < 26; i++)
{
replace(fileChars.begin(), fileChars.end(),indexb[i],indexa[i]);
}
for (int i = 0; i < fileChars.size(); i++)
{
decrypted<< fileChars[i];
}
其他可能的答案似乎是缓慢和低效的。
我能想到的最好的办法是:
- 遍历"加密"文本文件中的每个字符
- 找出当前字符位于"频率"数组中的哪个元素。您已经有
find_in_array()
函数来帮助您完成此操作。 - 写入位于"加密"秩数组索引中的字符
显然,您需要进行一些基本的错误检查,以确保不会在两个索引数组中查找非alpha字符。
下面是一些c++的例子:
char c;
int pos;
while (code.good())
{
code.get(c);
if ( (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') )
{
pos = find_in_array(indexb, c, 26);
decrypted << indexa[pos];
}
else
{
decrypted << c;
}
}
希望对你有帮助。
除非你想为你的字符使用wchar_t
,否则你就过于复杂了。你可以使用一个或两个数组(两个数组只有当你想要快速编码和解码;也可以用一个数组做所有的事情(类似于您尝试做的),但这更慢,更昂贵的性能方面)。
的想法是,做下面的事情。您应该能够做到这一点,而无需对现有代码进行任何重大更改(只需更改数组的设置和使用方式)。
char encoder[256];
char decoder[256];
现在以任何方式生成您的字典,对于每个字符,您应该得到以下两个变量,您将存储在这些数组中:
char from = 'a'; // the unencoded character
char to = 'x'; // the encoded character
// store them in the arrays for later use:
encoder[from] = to;
decoder[to] = from;
就是这样!要对字符串进行编码,请执行以下操作:
// these two could be pointers to buffers too
char my_string[] = "Hello World!";
char my_string_enc[256];
unsigned int p = 0;
while(my_string[p])
my_string_enc[p] = encoder[my_string[p++]];
my_string_enc[p] = ' '; // null terminating the encoded string
解码可以用类似的方式完成:
// these two could be pointers to buffers too
char my_string_enc[] = "...";
char my_string[256];
unsigned int p = 0;
while(my_string_enc[p])
my_string[p] = decoder[my_string_enc[p++]];
my_string[p] = ' '; // null terminating again
最好一次遍历要解密的字符串中的一个字符,然后更改这些字符。所以:
for (int i = 0; i < fileChars.size(); i++)
{
for(int j = 0; j < 26; j++){
if(fileChars[i]==indexb[j]){
fileChars[i]=indexa[j];
}
}
}
如果使用嵌套循环,效率会降低,但也可以。
相关文章:
- 动态分配的数组和静态数组之间的区别
- 删除[i] 数组和删除数组 [i] 之间的区别
- C++堆栈中数组之间的间隙
- 使用STD :: String和字符数组之间的选择
- 如何在不复制数据的情况下在平面数组和多维数组之间进行转换?
- 如果 strlen 在 char 数组之间遇到空格,它会怎么做
- 数组之间的特征行交叉积
- 为什么这两个实现多维数组之间会有如此巨大的执行时间差
- 字符指针和字符数组之间的区别
- 在一维和二维数组之间进行选择
- char阵列[]和char *数组之间有什么区别
- 为什么数组之间的==相等比较不起作用
- 为什么字符数组之间的这种比较不起作用?
- 分配器和 C++ 中内置数组之间的区别
- 无已知转换 在带有 std::vector 的无符号字符的 typedef 数组之间
- 链表和结构数组之间的区别
- 字符串对象和以 null 结尾的字符数组之间的差异
- 单指针数组和双指针数组之间的区别
- C++:反转数组中的字符串.在两个不同的数组之间交换字符串
- c++在3d数组之间传递双值