0

我正在尝试将字符串转换为大写,以便可以操作它,但是虽然我可以成功操作自然大写字符串,以及将小写转换为大写,但使用这种转换方法无法进行操作。

例如,如果我通过加密传递“hello”,我的加密字符串变为“HELLO”,但是当我通过“HELLO”(自然大写)时,它会正确移动。

是否有另一种强制大写的方法我需要使用或者我做错了什么?

int Caesar::encrypt (const std::string &message, std::string &emessage) {
  int count = 0;
  emessage = message;
  std::transform(emessage.begin(), emessage.end(), emessage.begin(), ::toupper);
  for (std::string::size_type i = 0; i < message.size(); i++) {
    for (int j = 0; j < 26; j++) {
      if (emessage[i] == std_alphabet[j]) {
        std::replace(emessage.begin(), emessage.end(), message[i], c_alphabet[j]);
      }
    }
    count++;
  }
  return count;
}

构造函数:

Caesar::Caesar (int shift) {
    // loop to populate vector with 26 letters of English alphabet
    // using ASCII uppcase letter codes
  for (int i = 0; i < 26; i++) {
    std_alphabet.push_back(i + 65);
  }
    // fills Caesar alphabet with standard generated alphabet
  c_alphabet = std_alphabet;
    // shifts Caesar alphabet based off the constructor parameter
  std::rotate(c_alphabet.begin(), c_alphabet.begin() + shift, c_alphabet.end());
}

测试文件:

void testCaesar() {
  Caesar test(4);
  std::string original = "HELLO";
  std::string encrypted = "";
  test.encrypt(original,encrypted);
  std::cout << encrypted << std::endl;
  std::cout << original << std::endl;
}

int main() {
  testCaesar();
  return 0;
}

显然有一个标题和包含的东西,但这是基本代码

头文件包含两个私有向量

4

1 回答 1

2

您看到的具体问题是您在这里替换了错误的东西:

std::replace(emessage.begin(), emessage.end(), message[i], c_alphabet[j]);

如果message是小写,那么emessage将是所有大写字母 - 都不是message[i]. 所以替换不会做任何事情。你的意思是:

std::replace(emessage.begin(), emessage.end(), emessage[i], c_alphabet[j]);
                                               ^^^^^^^^^^^

也就是说,您的算法完全错误,HELLO因为使用移位 4 进行加密BCBBA。字母上存在 1-1 映射,因此H不能L同时转到B. 您想要做的是移动每个字母,只需将其替换为下一个字母应该是什么。那是:

for (std::string::size_type i = 0; i < emessage.size(); ++i) {
    emessage[i] = c_alphabet[emessage[i] - 'A'];
}

您实际上不需要初始转换步骤:

emessage = message;
for (std::string::size_type i = 0; i < emessage.size(); ++i) {
    emessage[i] = c_alphabet[::toupper(emessage[i]) - 'A'];
}

count只需删除您的(这只是大小,因此是多余的)并按值获取消息,就可以大大缩短整个事情:

std::string encrypt(std::string from) { // intentionally copying
    for (char& c : from) {
        c = c_alphabet[::toupper(c) - 'A'];
    }
    return from;
}
于 2015-09-03T18:23:01.523 回答