XOR 错误结果,转义字符

XOR wrong result , escaping char

我正在尝试对一个小字符串进行异或运算,它有效。当我尝试使用异或字符串时,我什至无法编译它。

 string str = "MyNameIsMila";
 string str_xored = "2*&.8"'*"; //you can't escape this or the result be be different 
 //Enc:2*&.8"'*:
 //Dec:MyNameIsMila:

我试图对字符串进行转义,但最后我得到了另一个结果。 这有什么好的方向吗? 转义后输出:

//Enc:yamesila:
//Dec:2*&.8"'*:

希望找回 MyNameIsMila。

函数看起来像:

 string encryptDecrypt(string toEncrypt) {
     char key = 'K'; //Any char will work
     string output = toEncrypt;   
     for (int i = 0; i < toEncrypt.size(); i++)
         output[i] = toEncrypt[i] ^ key;
     return output;
 }

我有两件事要说:

1: The value of a string needs to be between 2 -> ""

 string str_xored = 2*&.8"'*;   //this is not a valid syntax = error

 //valid
 string str_xored = "2*&.8";
 str += '"';
 str += "'*";

2: In your case I would use iterators:

#include <iostream>
#include <string>

//please don't use "using namespace std;"

 std::string encryptDecrypt(std::string toEncrypt) {
     char key = 'K';            //Any char will work
     std::string output = "";   //needs to be   empty   

     for (auto i = toEncrypt.begin(); i != toEncrypt.end(); i++) {
        output += *i ^ key;     //*i holds the current character to see how
                                //an iterator works have a look at my link
     }
     return output;
 }


int main() {

    std::string str = encryptDecrypt("Hello...!");

    std::cout << str << std::endl;

    return 0;
}

这里看看(字符串)迭代器:

Link 1

Link 2

如果您认为迭代器太难,请使用您的

for(int i = 0; i < str.size(); i++){
    //CODE
}

for()-循环

您不能像处理普通字符串一样处理异或字符串!

value ^ same_value == 0

改为将它们视为普通容器。

示例:

#include <iostream>
#include <iterator>
#include <algorithm>

template<typename InputIterator, typename OutputIterator, typename Key>
void perform_xor(InputIterator begin, InputIterator end, OutputIterator out, Key const &key) {
    std::transform(begin, end, out, [key](auto &&value) { 
        return value ^ key;
    });
}

using namespace std;

int main() {
    char test[] = "(2*&.8\"\'*";

    perform_xor(begin(test), end(test), begin(test), '&');
    copy(begin(test), end(test), ostream_iterator<int>(cout, " ")); 

    cout << endl;

    perform_xor(begin(test), end(test), begin(test), '&');
    copy(begin(test), end(test), ostream_iterator<char>(cout)); 

    return 0;
}

参见:http://ideone.com/ryoNp5