0

我不明白为什么我的 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("");
}
4

1 回答 1

0

您可以通过将 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'))

于 2019-12-30T21:14:03.597 回答