为什么我的凯撒密码跳过某些字符?

时间:2019-10-25 12:19:03

标签: javascript string caesar-cipher

我有下面的代码使Caesar密码在每个输入字符上增加13个字符。它适用于几乎所有输入,但似乎会跳过随机字符。我似乎无法弄清楚为什么?!我仍在学习,所以任何帮助都会很棒!

输入是字符的编码字符串,每个字符向前移13位将被输出。预期的输出应该是可读的字符串。

如果我输入rot13('GUR DHVPX OEBJA SBK WHZCF BIRE GUR YNML QBT。'),我会期望“快速的棕色狐狸跳在懒惰的狗身上。”但是,相反,我得到的是“ T H E Q U I C K B R O W N F B X J H M P S B V R E G U R L A Z Y D B G。”

我很欣赏这可能是重复的,但是到目前为止,我仍无法找到这个特定问题的答案。

function rot13(str) {
  
  let newStr = [];

  for (let i = 0; i < str.length; i++) {
    let charNum = str.charCodeAt(i);
    console.log(charNum);
    if (charNum > 64 && charNum < 78) {
      let res = str.replace(str[i], String.fromCharCode(charNum + 13));
      newStr.push(res[i]);
    } else if (charNum > 77 && charNum < 91) {
      let res = str.replace(str[i], String.fromCharCode(charNum - 13));
      newStr.push(res[i]);
    } else {
      newStr.push(str[i]);
    }
  }

  console.log(newStr);
  return newStr.join(" ");
}

rot13('GUR DHVPX OEBJA SBK WHZCF BIRE GUR YNML QBT.');

2 个答案:

答案 0 :(得分:1)

String.fromCharCode(charNum + 13)String.fromCharCode(charNum - 13)就是您所需要的。您无需替换i中索引str处的字符。

newStr.push(String.fromCharCode(charNum + 13));
newStr.push(String.fromCharCode(charNum - 13));

答案 1 :(得分:0)

问题处于第二种状态:

let res = str.replace(str[i], String.fromCharCode(charNum - 13));

但即使没有这样做,您的代码也过度设计。修改过的版本

function rot13(str) {
  let newStr = [];

  for (let i = 0; i < str.length; i++) {
    let charNum = str.charCodeAt(i);
    //console.log(charNum);
    if (charNum > 64 && charNum < 78) {
      let res = String.fromCharCode(charNum + 13);
      newStr.push(res);
    } else if (charNum > 77 && charNum < 91) {
      let t = charNum + 13 - "Z".charCodeAt(0);
      let res = String.fromCharCode("A".charCodeAt(0) - 1 + t);
      newStr.push(res);
    } else {
      newStr.push(str[i]);
    }
  }

  return newStr.join(" ");
}

还有更好的解决方案,但是对于初学者,应该这样做。