我需要编写一个算法,给出一个十六进制字符串,生成一个包含4个十六进制数字的5个元素的数组和另一个包含2个十六进制数字长度的数组的数组。独特的两个前提是:
一个正确输出的示例:
字符串:87b86156d0000a4200005e02002f56614f7a2f54f7ebf45670ed62cbaa78e6f228297b0e7338215fb4
第一个数组:[“87b8”,“6156”,“d000”,“0a42”,“5e02”]
第二个数组:[“2f”,“56”]
我的方法是这样开始的:
var mystring = "87b86156d0970a4200005e02612f56614f7a2f54f7ebf45670ed62cbaa78e6f228297b0e7338215fb4"
var firststring = mystring.match(/.{1,4}/g);
这给了我:
[“87b8”,“6156”,“d097”,“0a42”,“0000”,...]
然后:
for (x=0;x<firststring.length;x++){
if (firststring[x]=="0000") {firststring.splice(x, 1)}
}
var secondstring = mystring.match(/.{1,2}/g);
这给了我:
[“87”,“b8”,“61”,“56”,“d0”,“97”......]
for (x=0;x<secondstring.length;x++){
if (secondstring[x]=="00") {secondstring.splice(x, 1)}
}
这里是我丢失的地方,我不知道如何编码我避免在两个阵列中使用的主要字符串数字(位置)的部分......
此致
答案 0 :(得分:1)
嗯,它不漂亮,但它有效:
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);
<强> JSBin 强>