1

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.

4
  • What did you try? Commented May 22, 2012 at 13:00
  • 2
    And what kind of NOT nice solutions you found? Commented May 22, 2012 at 13:00
  • If you know they are letters, can't you make a string and use its replace method? Commented May 22, 2012 at 13:07
  • From what I understand the question is how 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. It's not about simple chars replacement. Commented May 22, 2012 at 13:15

1 Answer 1

6

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();
    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.