簡體   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