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.
Asked
Active
Viewed 7,364 times
0
-
[What did you try](http://whatdidyoutry.com)? – Oded May 22 '12 at 13:00
-
2And what kind of NOT nice solutions you found? – Renatas M. May 22 '12 at 13:00
-
If you know they are letters, can't you make a string and use its replace method? – Davio May 22 '12 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. – Marek Musielak May 22 '12 at 13:15
1 Answers
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();
}

Marek Musielak
- 26,832
- 8
- 72
- 80