JS:如何将给定字符串中的每个字母在字母N个位置下移? [英] JS: how to shift each letter in the given string N places down in the alphabet?

查看:20
本文介绍了JS:如何将给定字符串中的每个字母在字母N个位置下移?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

how to shift each letter in the given string N places down in the alphabet? Punctuation, spaces, and capitalization should remain intact. For example if the string is "ac" and num is 2 the output should be "ce". What's wrong with my code? It converts letter to ASCII and adds given number then converts from ASCII to letter back. The last line replaces space.

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方法.试试:

You need to pass an argument to the fromCharCode method using the String object. Try:

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));

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

I had to modify the return statement, because it was introducing a bug for me

这篇关于JS:如何将给定字符串中的每个字母在字母N个位置下移?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆