[英]Javascript split string in different sized substrings
I need to code an algo that, giving a hex string,generates an array with 5 elements of 4 hex digits and another array with 2 elemetents of 2 hex digits long. 我需要编写一个算法,给出一个十六进制字符串,生成一个包含5个4个十六进制数字元素的数组,以及另一个包含2个2个十六进制数字元素的数组。 The unique two premises are:
唯一的两个前提是:
Example of one correct output: 一个正确输出的示例:
String : 87b86156d0000a4200005e02002f56614f7a2f54f7ebf45670ed62cbaa78e6f228297b0e7338215fb4 字符串:87b86156d0000a4200005e02002f56614f7a2f54f7ebf45670ed62cbaa78e6f228297b0e7338215fb4
first array: ["87b8", "6156", "d000", "0a42", "5e02"] 第一个数组:[“ 87b8”,“ 6156”,“ d000”,“ 0a42”,“ 5e02”]
second array: ["2f", "56"] 第二个数组:[“ 2f”,“ 56”]
My approach starts like this: 我的方法是这样开始的:
var mystring = "87b86156d0970a4200005e02612f56614f7a2f54f7ebf45670ed62cbaa78e6f228297b0e7338215fb4"
var firststring = mystring.match(/.{1,4}/g);
Which gives me: 这给了我:
["87b8", "6156", "d097", "0a42", "0000", ...] [“ 87b8”,“ 6156”,“ d097”,“ 0a42”,“ 0000”,...]
then: 然后:
for (x=0;x<firststring.length;x++){
if (firststring[x]=="0000") {firststring.splice(x, 1)}
}
var secondstring = mystring.match(/.{1,2}/g);
Which gives me: 这给了我:
["87", "b8", "61", "56", "d0", "97"...] [“ 87”,“ b8”,“ 61”,“ 56”,“ d0”,“ 97” ...]
for (x=0;x<secondstring.length;x++){
if (secondstring[x]=="00") {secondstring.splice(x, 1)}
}
Here is where i am lost, i don't know exactly how to code the part where i avoid the main string digits (positions) to be used in both arrays... 这是我迷路的地方,我不知道该如何编码避免在两个数组中使用主字符串数字(位置)的部分。
Regards, 问候,
Well, it's not pretty, but it works: 好吧,它并不漂亮,但是可以工作:
var str = "87b86156d0970a4200005e02612f56614f7a2f54f7ebf45670ed62cbaa78e6f228297b0e7338215fb4";
var grabLength = 4,
// 4-char strings
grp1 = [],
// 2-char strings
grp2 = [],
chunk;
while(chunk = str.slice(0, grabLength)) {
str = str.slice(grabLength);
// skip all zeros
if (/^0+$/.test(chunk)) continue;
if (grabLength === 4) {
if (grp1.push(chunk) === 5) {
grabLength = 2;
}
continue;
}
// skip 2-char sequences that match the start of a 4-char sequence
var hasMatch = false;
for (var i = 0; i < grp1.length; i++) {
if (chunk === grp1[i].slice(0, 2)) {
hasMatch = true;
continue;
}
}
if (hasMatch) continue;
grp2.push(chunk);
if (grp2.length === 2) break;
}
console.log(grp1);
console.log(grp2);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.