我想把一个非常大的字符串(比如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可以实现这样的事情吗如果可以,从性能来看,这是最好的方式吗?
当前回答
这是一个快速而直接的解决方案
function chunkString (str, len) { const size = Math.ceil(str.length/len) const r = Array(size) let offset = 0 for (let i = 0; i < size; i++) { r[i] = str.substr(offset, len) offset += len } return r } console.log(chunkString("helloworld", 3)) // => [ "hel", "low", "orl", "d" ] // 10,000 char string const bigString = "helloworld".repeat(1000) console.time("perf") const result = chunkString(bigString, 3) console.timeEnd("perf") console.log(result) // => perf: 0.385 ms // => [ "hel", "low", "orl", "dhe", "llo", "wor", ... ]
其他回答
使用npm库"chkchars" 但是请记住,要确保给定的字符串长度完全除以“number”参数。
const phrase = "1110010111010011100101110100010000011100101110100111001011101001011101001110010111010001000001110010111010011100101110100"
const number = 7
chkchars.splitToChunks(phrase, number)
// result => ['1110010', '1110100','1110010', '1110100','0100000', '1110010','1110100', '1110010','1110100', '1011101','0011100', '1011101','0001000','0011100','1011101', '0011100','1011101']
// perf => 0.287ms
你可以这样做:
"1234567890".match(/.{1,2}/g);
// Results in:
["12", "34", "56", "78", "90"]
如果字符串的大小不是chunk-size的倍数,该方法仍然有效:
"123456789".match(/.{1,2}/g);
// Results in:
["12", "34", "56", "78", "9"]
一般来说,对于任何你想要提取最多n个子字符串的字符串,你可以这样做:
str.match(/.{1,n}/g); // Replace n with the size of the substring
如果你的字符串可以包含换行符或回车,你会这样做:
str.match(/(.|[\r\n]){1,n}/g); // Replace n with the size of the substring
至于性能,我用了大约10k个字符,在Chrome上花了一秒钟多一点的时间。YMMV。
这也可以用在可重用函数中:
function chunkString(str, length) {
return str.match(new RegExp('.{1,' + length + '}', 'g'));
}
我会用正则表达式…
var chunkStr = function(str, chunkLength) {
return str.match(new RegExp('[\\s\\S]{1,' + +chunkLength + '}', 'g'));
}
这是一个解决方案,我想出了一个模板字符串后,一个小实验:
用法:
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
它将大字符串拆分为给定单词的小字符串。
function chunkSubstr(str, words) {
var parts = str.split(" ") , values = [] , i = 0 , tmpVar = "";
$.each(parts, function(index, value) {
if(tmpVar.length < words){
tmpVar += " " + value;
}else{
values[i] = tmpVar.replace(/\s+/g, " ");
i++;
tmpVar = value;
}
});
if(values.length < 1 && parts.length > 0){
values[0] = tmpVar;
}
return values;
}