如何将字符串分成字母然后推入下一个字母?
How to do string divided into letters then push into the next letter?
let output ="I am a string"
const app=output.split("")
console.log(app)
//输出
(13) [
“我”,
" ",
“一种”,
“米”,
" ",
“一种”,
" ",
"s",
“吨”,
"r",
“一世”,
"n",
“G”
]
然后它需要按字母顺序将每个字母更改为下一个字母
这意味着
"j","","b","n","","b,","","t","u","s","j","o" ,"h
之后字符串必须这样写;
“jbnbtusjoh”
有什么意见吗?
拆分后,映射字符数组,将每个字符转换为代码(如果不是space),添加一个,并将代码转换回字符:
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)
为什么不将每个字符转换为 ASCII,然后简单地增加数字?
好的,让我们一步一步来:
// 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)
let output ="I am a string"
const app=output.split("")
console.log(app)
//输出 (13) [ “我”, " ", “一种”, “米”, " ", “一种”, " ", "s", “吨”, "r", “一世”, "n", “G” ]
然后它需要按字母顺序将每个字母更改为下一个字母
这意味着
"j","","b","n","","b,","","t","u","s","j","o" ,"h
之后字符串必须这样写; “jbnbtusjoh”
有什么意见吗?
拆分后,映射字符数组,将每个字符转换为代码(如果不是space),添加一个,并将代码转换回字符:
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)
为什么不将每个字符转换为 ASCII,然后简单地增加数字?
好的,让我们一步一步来:
// 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)