繁体   English   中英

用一个其他序列替换一个字节序列的最有效方法

[英]Most efficient way to replace one sequence of the bytes with some other sequence

用一个字节的其他序列(例如90)替换一个字节序列(例如67 67 67)的最有效方法是什么。 序列可以具有不同的长度。

这是一个简短的应用程序,可以满足您的需求:

    static void Main(string[] args)
    {
        byte [] bArray = new byte[] {11, 67, 67, 67, 33, 34, 67, 67, 11, 33, 67, 67, 67, 67};

        byte[] result = Replace(bArray, new byte[] {67, 67, 67}, new byte[] {90});

        foreach (byte b in result)
        {
            Console.WriteLine(b);
        }
    }

    private static byte [] Replace(byte[] input, byte[] pattern, byte[] replacement)
    {
        if (pattern.Length == 0)
        {
            return input;
        }

        List<byte> result = new List<byte>();

        int i;

        for (i = 0; i <= input.Length - pattern.Length; i++)
        {
            bool foundMatch = true;
            for (int j = 0; j < pattern.Length; j++)
            {
                if (input[i + j] != pattern[j])
                {
                    foundMatch = false;
                    break;
                }
            }

            if (foundMatch)
            {
                result.AddRange(replacement);
                i += pattern.Length - 1;
            }
            else
            {
                result.Add(input[i]);
            }
        }

        for (; i < input.Length; i++ )
        {
            result.Add(input[i]);
        }

        return result.ToArray();
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM