替换两个不同数组之间的字符

Replace characters between two different arrays C++

本文关键字:数组 之间 字符 两个 替换      更新时间:2023-10-16

我有两个字母表数组,它们以两种不同的方式按我需要的顺序排序。现在我需要按照顺序,将索引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];
                }

其他可能的答案似乎是缓慢和低效的。

我能想到的最好的办法是:

  1. 遍历"加密"文本文件中的每个字符
  2. 找出当前字符位于"频率"数组中的哪个元素。您已经有find_in_array()函数来帮助您完成此操作。
  3. 写入位于"加密"秩数组索引中的字符

显然,您需要进行一些基本的错误检查,以确保不会在两个索引数组中查找非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];
        }
    }
}

如果使用嵌套循环,效率会降低,但也可以。