【问题标题】:Javascript - Shift characters of a string from n placesJavascript - 从 n 个位置移动字符串的字符
【发布时间】:2017-09-07 23:43:27
【问题描述】:

问题是对于给定的字符串,我必须将每个字母从给定的数字位置移动。

例如,

Encrypt(‘ABC’, 4) should return "EFG"
Encrypt("AB C", 2) Should equal to “CD E”
Encrypt("ABC DEF", 2) Should equal to “CDE FGH”

这是我想出的解决方案;

function encrypt(str, index) {
    var encryptedstr = '';
    var charCode = 0;

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

        if (charCode >= 65 && charCode <= 77 ){
            encryptedstr += String.fromCharCode(charCode + index);
        }else{
            encryptedstr += String.fromCharCode(charCode);
        }
    }
    return encryptedstr;
}

这适用于给定的输入。但它一直告诉我“答案应该对任何给定的输入都有效。”我在这里做错了什么?

我将代码更改如下,但它也给了我同样的错误。

for (var i = 0; i < str.length; i++) 
{
    if(str[i] === " ")
    {
        encryptedstr += " ";  
    }else{
        charCode = (str[i].charCodeAt()) + index;
        encryptedstr += String.fromCharCode(charCode);
    }        
}

【问题讨论】:

  • 您是否提供了有关您应该能够处理的输入类型的任何信息?小写字符呢?
  • “但它一直在告诉我” 是谁或什么?它对哪个输入失败?
  • 例如,您可能需要将Z 转换为D
  • @Hamms 输入的字符串总是大写的。
  • Z 的字符码不是 77。

标签: javascript string


【解决方案1】:

之前我没有涵盖所有约束。这就是为什么它不起作用。我还必须考虑非字母字符。我在不同的帖子中找到了解决方案。

If you have same problem go to this link and follow the answer.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-19
    • 1970-01-01
    • 2018-12-23
    • 2022-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多