0

1 つのバイト シーケンス (67 67 67 など) を別のバイト シーケンス (90 など) に置き換える最も効率的な方法は何ですか。シーケンスの長さは異なる場合があります。

4

1 に答える 1

6

必要なことを行う短いアプリを次に示します。

    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();
    }
于 2012-05-22T13:22:25.830 に答える