如何将给定字符串中的每个字母在字母表中向下移动 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
最佳答案
您需要使用 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));
我不得不修改返回语句,因为它给我引入了一个错误
关于javascript - JS : how to shift each letter in the given string N places down in the alphabet?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33084862/