加密字符串的功能不起作用

时间:2015-04-17 20:30:27

标签: c++

我已创建此功能来加密字符串,但它不起作用。

软件搜索字符串的每个字符" s"在主要内容中,只需找到它(在字符串z1和z2中)将其替换为前面三个位置的字符

#include <iostream>
#include <string>
using namespace std;

string change(string& inp)
{

    string z1 = {"abcdefghilmnopqrtsvzabc"};
    string z2 = {"ABCDEFGHILMNOPQRSTUVZABC"};

    for(char c : inp)
    {
        if(z1.find(c) != string::npos) //string::npos is the "false" member 
        {
            auto x = z1.find(c);       //returned by **z1.find(c)**
            c = z1[x + 3];
            // The software searches each character, just find it (in strings z1 and z2) 
            // replaces it with the character in three positions more ahead
        }
        else
        {
            auto y = z2.find(c);
            c = z2[y + 3];
        }
    }
    return inp;
}

int main()
{
    string s = {"abcd"};

    cout << change(s) << endl;
}

1 个答案:

答案 0 :(得分:0)

你的for循环没有引用字符串中的字符,你得到一个带有字符值的变量c。操作c不会更改给定的字符串inp。将您的循环从c ++ 11样式更改为:

for(int i=0;i<inp.length();i++ ){                       
    if(z1.find(inp[i])!=string::npos){       //string::npos is the "false" member 
        auto x =z1.find(inp[i]);             //returned by **z1.find(c)**
        inp[i]=z1[x+3];                      
                                         //The software searches each character, just find it (in strings z1 and z2) 
    }                                    //replaces it with the character in three positions more ahead
    else                                
    {
        auto y=z2.find(inp[i]);
        inp[i]=z2[y+3];
    }
}

PS:我尝试尽可能少地更改给定代码。不为给定问题或其他可能的错误提供最佳解决方案。

<强>更新

themagiciant95(提问)自己找到了一个更好的解决方案:

for(char &c:inp){ 

我错过了。