【问题标题】:Replace specific characters in line, c++替换行中的特定字符,c ++
【发布时间】:2012-01-30 21:04:00
【问题描述】:

我正在开发一个使用特定密钥解密文本的程序。我正在尝试使用replace(),但它似乎不起作用。比如qwert应该解密成hello,但是输出是hlllo;在这种情况下,qwert 中的w 被解密为e,但随后又被重新解密为l

输入:

 xnm ceuob lrtzv ita hegfd tsmr xnm ypwq ktj
 should come out as:
 the quick brown fox jumps over the lazy dog
 I'm getting:
 oga yaacd brozn aox gamav ovar oga lazy dog

我该如何解决这个问题?

int main()
{
    // ...
    myFile.open("decrypt.txt");
    while (myFile.good()) 
    {
        getline(myFile, line2);
        // now line2 is, e.g., "xnm ceuob lrtzv ita hegfd tsmr xnm ypwq ktj"

        // help here
        for (int i = 0; i < 26; i++) 
        {
            replace(line2.begin(), line2.end(), key[i], fox[i]);
        }
        v.push_back(line2);
    }

    myFile.close();

    for (int i = 0; i < numline; i++) 
    {
        cout << "line " << i <<" = " << v[i] << endl;
    }

    return 0;
}

【问题讨论】:

  • 好的,我删除了所有不必要的代码并解释得更好。

标签: c++ replace char character


【解决方案1】:

通过进行 26 次单独的替换,后面的替换在前面替换的结果之上。您需要找到一种方法,使每个字符的每个替换只发生一次。

【讨论】:

  • 每个字符执行一次的技巧是有两个字符串,一个源和一个目标,并从一个转换为另一个。
  • 我正在尝试使用 replace_copy 但是当我 cout v 时它是空的,好像它没有复制到 line3 for (int i=0;i&lt;26;i++) { replace_copy(line2.begin(), line2.end(),line3.begin(), key[i], fox[i]); } v.push_back( line3 );
【解决方案2】:

您需要对每个字符进行一次解密。除了有两个数组keyfox,它们(显然)包含要替换的字符,您可以考虑在输入字符和它们的解密版本之间构建一个map。然后你可以简单地遍历输入字符串,一次解密一个字符。

std::map<char, char> lookup; 
// populate lookup such that lookup['q'] = 'h', lookup['w'] = 'e', etc.

// walk over line2, decrypting a character at a time.
for (int i = 0; i < line2.length(); i++)
{
    char c = line2[i];
    char d = lookup[c];
    line2[i] = d;
    // or, if you want to keep it on one line:
    // line2[i] = lookup[line2[i]];
}

【讨论】:

    【解决方案3】:

    在 C++ 中,您可以使用方括号访问和修改字符串元素。例如:

    String str("dog");
    str[1] = 'c';
    //str = "dcg"
    

    所以你可以使用这个符号来代替replace()。如果替换没有按您的预期工作,那么您的密钥可能是错误的。

    【讨论】:

    • 这是真的,但这不是问题所在。替换实际上只是包装了多个作业。
    猜你喜欢
    • 2022-01-05
    • 2015-10-18
    • 2017-11-23
    • 2012-08-09
    • 2012-01-07
    • 2017-11-26
    • 1970-01-01
    相关资源
    最近更新 更多