【问题标题】:How to do string divided into letters then push into the next letter?如何将字符串分成字母然后推入下一个字母?
【发布时间】:2021-11-18 21:51:15
【问题描述】:
let output ="I am a string"

const app=output.split("")

console.log(app)

//输出 (13) [ “一世”, " ", “一种”, “米”, " ", “一种”, " ", "s", "t", "r", “一世”, "n", “G” ]

然后它需要按字母顺序将每个字母更改为下一个字母

意思是

"j","","b","n","","b,","","t","u","s","j","o"," h"

之后字符串必须写成 ; "jbnbtusjoh"

有什么意见吗?

【问题讨论】:

    标签: javascript arrays string replace split


    【解决方案1】:

    好的,让我们一步一步来:

    // first the string
    let out = "I am a string"
    // convert to array 
    let arOut = out.split("") // gives ["I"," ", "a", "m", " ", "a"....]
    // now lets get cracking : 
    
    let mapped = arOut.map(element => element == ' ' ? element : String.fromCharCode(element.charCodeAt(0)+1))
    // this get char code of element and then adds one and gets equivalent char ignores space
    
    let newOut = mapped.join("") // we have our result
    
    console.log(newOut)

    【讨论】:

    • 感谢它正在工作,我想反馈,但我没有 15 名声望,这就是它不反馈的原因
    • @LiamEdwardRobinson:没问题,很乐意提供帮助。如果它帮助你可以接受答案之一(勾号)
    【解决方案2】:

    为什么不将每个字符转换为 ASCII,然后简单地增加数字?

    【讨论】:

    • 我不知道,但这是有道理的,
    • Idk,我无法反馈。 Bc 我没有足够的声誉
    【解决方案3】:

    拆分后,映射字符数组,将每个字符转换为代码(如果不是空格),加一,将代码转换回字符:

    const output = 'I am a string'
    
    const result = output.split('')
      .map(c => c === ' ' 
        ? c // ignore spaces
        : String.fromCharCode(c.charCodeAt(0) + 1) // convert char to code, add one, and convert back to char
      )
      .join('') // if you need a string
    
    console.log(result)

    您也可以使用Array.from() 直接将字符串转换为转换后的字符数组:

    const output = 'I am a string'
    
    const result = Array.from(
      output,
      c => c === ' ' ? c : String.fromCharCode(c.charCodeAt(0) + 1)
    ).join('')
    
    console.log(result)

    【讨论】:

    • 谢谢它顺利运行,我没有 15 声望,所以它没有反馈
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多