用一个其他序列替换一个字节序列的最有效方法 [英] Most efficient way to replace one sequence of the bytes with some other sequence

查看:74
本文介绍了用一个其他序列替换一个字节序列的最有效方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

What is the most efficient way to replace one sequence of the bytes (eg 67 67 67) with some other sequence of the bytes (eg 90). The sequences can have different length.

推荐答案

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

Here is a short app which does what you need:

    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();
    }

这篇关于用一个其他序列替换一个字节序列的最有效方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆