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

问题描述 投票:0回答:2

我有下面的代码,用于使凯撒密码在每个输入字符上增加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.');
javascript string caesar-cipher
2个回答
1
投票

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

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

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(" ");
}

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

© www.soinside.com 2019 - 2024. All rights reserved.