我正在进行一项挑战,要求在字符串中以特定的时间间隔插入新的行字符。预期回报的例子:
insertNewLine('Happiness takes wisdom and courage', 20) => 'Happiness takes\nwisdom and courage'
insertNewLine('Happiness takes wisdom and courage', 30) => 'Happiness takes wisdom and\ncourage'
到目前为止,我一直在考虑实现一个简单的算法:
显然算法是有缺陷的,因为这是我得到的回报,主要是因为我循环遍历字符串块的数组并且总是在每个块中添加换行符。这是正确的输出:
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('');
}
};
答案 0 :(得分:1)
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);
}
答案 1 :(得分:0)
试试这个
function insertNewLine(str, pos){
var str = str.split("")
for (var i = pos-1; i < str.length-1; i+=pos) {
str[i] = "\n"
}
return str.join("")
}