JS:如何将给定字符串中的每个字母在字母表中向下移动 N 位?

新手上路,请多包涵

如何将给定字符串中的每个字母在字母表中向下移动 N 位?标点符号、空格和大小写应保持不变。例如,如果字符串为“ac”且 num 为 2,则输出应为“ce”。我的代码有什么问题?它将字母转换为 ASCII 并添加给定数字,然后从 ASCII 转换为回字母。最后一行替换空格。

 function CaesarCipher(str, num) {

    str = str.toLowerCase();
    var result = '';
    var charcode = 0;

    for (i = 0; i < str.length; i++) {
        charcode = (str[i].charCodeAt()) + num;
        result += (charcode).fromCharCode();
    }
    return result.replace(charcode.fromCharCode(), ' ');

}

我越来越

TypeError: charcode.fromCharCode is not a function

原文由 Sammy 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 365
2 个回答

您需要使用 String 对象将参数传递给 fromCharCode 方法。尝试:

 function CaesarCipher(str, num) {
    // you can comment this line
    str = str.toLowerCase();

    var result = '';
    var charcode = 0;

    for (var i = 0; i < str.length; i++) {
        charcode = (str[i].charCodeAt()) + num;
        result += String.fromCharCode(charcode);
    }
    return result;

}
console.log(CaesarCipher('test', 2));

我不得不修改返回语句,因为它为我引入了一个错误

原文由 Ally Rippley 发布,翻译遵循 CC BY-SA 4.0 许可协议

需要考虑将字母表中的最后一个字母移回开头的事实。这是我的看法:

 var input = "Caesar Cipher";

function CaesarCipher(str, num) {
    var alphabet = "abcdefghijklmnopqrstuvwxyz";
    var newStr = "";

    for (var i = 0; i < str.length; i++) {
        var char = str[i],
            isUpper = char === char.toUpperCase() ? true : false;

        char = char.toLowerCase();

        if (alphabet.indexOf(char) > -1) {
            var newIndex = alphabet.indexOf(char) + num;
            if(newIndex < alphabet.length) {
              isUpper ? newStr += alphabet[newIndex].toUpperCase() : newStr += alphabet[newIndex];
            } else {
              var shiftedIndex = -(alphabet.length - newIndex);
                isUpper ? newStr += alphabet[shiftedIndex].toUpperCase() : newStr += alphabet[shiftedIndex];
            }
        } else {
           newStr += char;
        }
    }
    return newStr;
}

console.log(CaesarCipher(input, 20));

JSFiddle

原文由 robjez 发布,翻译遵循 CC BY-SA 4.0 许可协议

推荐问题