繁体   English   中英

无法弄清楚为什么我的 ROT13 转换器可以使用小写字母但不能使用大写字母

[英]Can't figure out why my ROT13 converter works with lowercase but it doesn't work with uppercase

我不明白为什么我的 ROT13 转换器不能使用大写字母。 它适用于小写字母。 我一直试图找到这个问题一段时间,但没有运气..感谢您的帮助。

这是代码


var rot13 = str => {

  let alphabet = 'abcdefghijklmnopqrstuvwxyz';
  let alphabetUp = alphabet.toUpperCase();
  let ci = [];

  for (let i = 0; i < str.length; i++) {

    let index = alphabet.indexOf(str[i]);


    // for symbols
    if (!str[i].match(/[a-z]/ig)) {

      ci.push(str[i])
      // for letters A to M
    } else if (str[i].match(/[A-M]/ig)) {
      //lowercase
      if (str[i].match(/[a-m]/g)) {
        ci.push(alphabet[index + 13])
        //uppercase (doensn't work)       
      } else if (str[i].match(/[A-M]/g)) {
        ci.push(alphabetUp[index + 13])
      }
      // for letters N to Z
    } else if (str[i].match(/[n-z]/ig)) {
      //lowercase
      if (str[i].match(/[n-z]/g)) {
        ci.push(alphabet[index - 13])
        //uppercase (doensn't work)       
      } else if (str[i].match(/[N-Z]/g)) {
        ci.push(alphabetUp[index - 13])
      }
    }

  }

  return ci.join("");
}

您可以通过将 13 添加到索引并使用模 26 来获取新索引然后检查原始字母是否为大写来轻松完成。 尝试这个

 const rot13 = str => { let alphabet = 'abcdefghijklmnopqrstuvwxyz'; let newstr = [...str].map(letter => { let index = alphabet.indexOf(letter.toLowerCase()); if(index === -1) { return letter; } index = (index + 13) % 26; return letter === letter.toUpperCase() ? alphabet[index].toUpperCase() : alphabet[index]; }) return newstr.join(""); } console.log(rot13('hello'))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM