c#一串数组,{FA,AF,00,03,00,31,31,33,FA,AF,00,02,00,34,35............}
数组长度不固定,首先找到FA,AF为特征值的两个元素,然后删除当前的两个元素以及后面的三个元素,也就是说删除FA,AF,00,03,00和FA,AF,00,02,00,剩下的元素重新生成一个数组。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
byte[] arr = { 0xFA, 0xAF, 0x00, 0x03, 0x00, 0x31, 0x31, 0x33, 0xFA, 0xAF, 0x00, 0x02, 0x00, 0x34, 0x35 };
List<int> toRemove = new List<int>() { };
bool fa = false;
for (int i = 0; i < arr.Length; i++)
{
if (arr[i] == 0xFA) { fa = true; continue; }
if (arr[i] == 0xAF && fa) { toRemove.AddRange(Enumerable.Range(i - 1, 5)); i += 3; fa = false; };
}
arr = arr.Select((x, i) => new { x, i }).Where(x => !toRemove.Contains(x.i)).Select(x => x.x).ToArray();
Console.WriteLine(string.Join(" ", arr.Select(x => x.ToString("X2"))));
}
}
}
31 31 33 34 35
Press any key to continue . . .
你这串数据主要应用于什么场景的?如果是通讯场景,这么用不合适会有大量内存碎片,建议遍历一次,查出并保存FA,AF开头的索引号,通过索引号数量知道了新字符串长度,new byte[]相应长度的数组,再使用Buffer.BlockCopy复制进新数组
foreach循环遍历,简单粗暴,然后自己设置条件重新组合个新的列表好了
如果数组长度不是很长,建议使用 String.Join 方法拼成逗号分隔的字符串,接着用正则表达式干掉,然后再 Split 成数组返回