我想把一个非常大的字符串(比如10,000个字符)分割成n大小的块。
就性能而言,最好的方法是什么?
例如: "1234567890"除以2将变成["12","34","56","78","90"]。
使用string。prototype。match可以实现这样的事情吗如果可以,从性能来看,这是最好的方式吗?
我想把一个非常大的字符串(比如10,000个字符)分割成n大小的块。
就性能而言,最好的方法是什么?
例如: "1234567890"除以2将变成["12","34","56","78","90"]。
使用string。prototype。match可以实现这样的事情吗如果可以,从性能来看,这是最好的方式吗?
当前回答
我创建了几个更快的变体,您可以在jsPerf上看到。我最喜欢的是这个:
function chunkSubstr(str, size) {
const numChunks = Math.ceil(str.length / size)
const chunks = new Array(numChunks)
for (let i = 0, o = 0; i < numChunks; ++i, o += size) {
chunks[i] = str.substr(o, size)
}
return chunks
}
其他回答
我对上述解决方案的问题是,不管在句子中的位置如何,它都将字符串划分为正式的大小块。
我认为下面的方法比较好;虽然它需要一些性能调整:
static chunkString(str, length, size,delimiter='\n' ) {
const result = [];
for (let i = 0; i < str.length; i++) {
const lastIndex = _.lastIndexOf(str, delimiter,size + i);
result.push(str.substr(i, lastIndex - i));
i = lastIndex;
}
return result;
}
window.format = function(b, a) {
if (!b || isNaN(+a)) return a;
var a = b.charAt(0) == "-" ? -a : +a,
j = a < 0 ? a = -a : 0,
e = b.match(/[^\d\-\+#]/g),
h = e && e[e.length - 1] || ".",
e = e && e[1] && e[0] || ",",
b = b.split(h),
a = a.toFixed(b[1] && b[1].length),
a = +a + "",
d = b[1] && b[1].lastIndexOf("0"),
c = a.split(".");
if (!c[1] || c[1] && c[1].length <= d) a = (+a).toFixed(d + 1);
d = b[0].split(e);
b[0] = d.join("");
var f = b[0] && b[0].indexOf("0");
if (f > -1)
for (; c[0].length < b[0].length - f;) c[0] = "0" + c[0];
else +c[0] == 0 && (c[0] = "");
a = a.split(".");
a[0] = c[0];
if (c = d[1] && d[d.length -
1].length) {
for (var d = a[0], f = "", k = d.length % c, g = 0, i = d.length; g < i; g++) f += d.charAt(g), !((g - k + 1) % c) && g < i - c && (f += e);
a[0] = f
}
a[1] = b[1] && a[1] ? h + a[1] : "";
return (j ? "-" : "") + a[0] + a[1]
};
var str="1234567890";
var formatstr=format( "##,###.", str);
alert(formatstr);
This will split the string in reverse order with comma separated after 3 char's. If you want you can change the position.
我创建了几个更快的变体,您可以在jsPerf上看到。我最喜欢的是这个:
function chunkSubstr(str, size) {
const numChunks = Math.ceil(str.length / size)
const chunks = new Array(numChunks)
for (let i = 0, o = 0; i < numChunks; ++i, o += size) {
chunks[i] = str.substr(o, size)
}
return chunks
}
这是一个解决方案,我想出了一个模板字符串后,一个小实验:
用法:
chunkString(5)`testing123`
函数chunkString(nSize) return (strToChunk) => { Let result = []; let chars = String(strToChunk).split("); 对于(设I = 0;i < (String(strToChunk)。length / nSize);我+ +){ result = result.concat(char .slice(i*nSize,(i+1)*nSize).join(")); } 返回结果 } } document . write (chunkString(5)“testing123”); //返回:testi,ng123 document . write (chunkString(3)“testing123”); //返回:tes,tin,g12,3
var str = "123456789";
var chunks = [];
var chunkSize = 2;
while (str) {
if (str.length < chunkSize) {
chunks.push(str);
break;
}
else {
chunks.push(str.substr(0, chunkSize));
str = str.substr(chunkSize);
}
}
alert(chunks); // chunks == 12,34,56,78,9