单表置换加密即让原符号与新符号一一对应,进而对用原符号组成的符号串进行加密。
    加密

    1. //加密
    2. int encrypt(string& sentence)
    3. {
    4. int location;
    5. string key = "qazwsxedcrfvtgbyhnujmikolpQAZWSXEDCRFVTGBYHNUJMIKOLP";
    6. string alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; //对应的置换单表,可进行修改
    7. for (int i = 0; i < sentence.length(); i++)
    8. {
    9. location = alphabet.find_first_of(sentence[i]);
    10. if (location != -1) //非英文字母不加密
    11. {
    12. sentence[i] = key[location];
    13. }
    14. }
    15. return 1;
    16. }

    解密

    1. //解密
    2. int decipher(string& sentence)
    3. {
    4. int location;
    5. string key = "qazwsxedcrfvtgbyhnujmikolpQAZWSXEDCRFVTGBYHNUJMIKOLP";
    6. string alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    7. for (int i = 0; i < sentence.length(); i++)
    8. {
    9. location = key.find_first_of(sentence[i]);
    10. if (location != -1)
    11. {
    12. sentence[i] = alphabet[location];
    13. }
    14. }
    15. return 1;
    16. }

    完整代码

    1. #include<bits/stdc++.h>
    2. using namespace std;
    3. //单表代替密码
    4. //find_first_of()
    5. //在母串上从指定位置开始查找,
    6. //如果遇到的字符与目标串中任意字符相同,则查找成功,返回该字符的位置。
    7. //若没有,返回-1
    8. //加密
    9. int encrypt(string& sentence)
    10. {
    11. int location;
    12. string key = "qazwsxedcrfvtgbyhnujmikolpQAZWSXEDCRFVTGBYHNUJMIKOLP";
    13. string alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; //对应的置换单表,可进行修改
    14. for (int i = 0; i < sentence.length(); i++)
    15. {
    16. location = alphabet.find_first_of(sentence[i]);
    17. if (location != -1) //非英文字母不加密
    18. {
    19. sentence[i] = key[location];
    20. }
    21. }
    22. return 1;
    23. }
    24. //解密
    25. int decipher(string& sentence)
    26. {
    27. int location;
    28. string key = "qazwsxedcrfvtgbyhnujmikolpQAZWSXEDCRFVTGBYHNUJMIKOLP";
    29. string alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    30. for (int i = 0; i < sentence.length(); i++)
    31. {
    32. location = key.find_first_of(sentence[i]);
    33. if (location != -1)
    34. {
    35. sentence[i] = alphabet[location];
    36. }
    37. }
    38. return 1;
    39. }
    40. int main()
    41. {
    42. string sentence;
    43. //cout << "请输入要加密的文字:" << endl;
    44. //getline(cin, sentence);
    45. sentence = " Time waits for no man !";
    46. encrypt(sentence);
    47. cout << "加密后" << endl;
    48. cout << sentence << endl;
    49. decipher(sentence);
    50. cout << "解密后" << endl;
    51. cout << sentence << endl;
    52. }