gpt4 book ai didi

javascript - 如何在字符串中以正确的间隔插入换行符?

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:55:50 29 4
gpt4 key购买 nike

我正在应对一项要求在字符串中以特定间隔插入新行字符的挑战。预期返回示例:

insertNewLine('Happiness takes wisdom and courage', 20) => 'Happiness takes\nwisdom and courage'

insertNewLine('Happiness takes wisdom and courage', 30) => 'Happiness takes wisdom and\ncourage'

到目前为止,我一直在想一个容易实现的算法是这样的:

  • 将字符串拆分成相等的 block ,传递所需的宽度
  • 在每个chunk中找到最后一个空间索引并替换为\n

显然该算法存在缺陷,因为这是我得到的返回,主要是因为我在字符串 block 数组上循环,并且总是在每个 block 中添加一个换行符。这是正确的输出:

insertNewLine('Happiness takes wisdom and courage', 20) => 'Happiness takes\nwisdom and\ncourage'

什么是更好的算法来达到预期的结果?

代码如下:

const _ = require('underscore')
const insertNewLine = (text, width) => {
if (width < 15) return 'INVALID INPUT';
if (text.length <= width) return text;
else {
const arrayOfText = text.split('');
const temparray = [];
for (let i = 0; i < arrayOfText.length; i += width) {
temparray.push(arrayOfText.slice(i, i + width));
}
return temparray.map((elem, i, arr) => {
elem[_.lastIndexOf(elem, ' ')] = '\n';
return elem.join('');
}).join('');
}
};

最佳答案

function replaceSpace(tx,n) { //tx is the text and n is the number
var br=0;
while(n-->0) {
if(tx[n]==" ") {
br = n;
break;
}
}
return tx.substring(0,br)+"\n"+tx.substring(br,tx.length);
}

关于javascript - 如何在字符串中以正确的间隔插入换行符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46278395/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com