Hier ist meine Implementierung von BMH-Algorithmus (es wirkt wie ein Zauber):Boyer-Moore-Horspool Algorithmus für alle Spiele (Finden Byte-Array innerhalb Byte-Array)
public static Int64 IndexOf(this Byte[] value, Byte[] pattern)
{
if (value == null)
throw new ArgumentNullException("value");
if (pattern == null)
throw new ArgumentNullException("pattern");
Int64 valueLength = value.LongLength;
Int64 patternLength = pattern.LongLength;
if ((valueLength == 0) || (patternLength == 0) || (patternLength > valueLength))
return -1;
Int64[] badCharacters = new Int64[256];
for (Int64 i = 0; i < 256; ++i)
badCharacters[i] = patternLength;
Int64 lastPatternByte = patternLength - 1;
for (Int64 i = 0; i < lastPatternByte; ++i)
badCharacters[pattern[i]] = lastPatternByte - i;
// Beginning
Int64 index = 0;
while (index <= (valueLength - patternLength))
{
for (Int64 i = lastPatternByte; value[(index + i)] == pattern[i]; --i)
{
if (i == 0)
return index;
}
index += badCharacters[value[(index + lastPatternByte)]];
}
return -1;
}
Ich habe versucht, es zu ändern, um zu gib alle Treffer zurück anstatt nur den ersten Index, aber ich bekomme IndexOutOfRangeException überall D:
Offensichtlich fehlt mir etwas Wichtiges oder ich habe nicht richtig verstanden, wie es funktioniert. Was mache ich falsch?
public static List<Int64> IndexesOf(this Byte[] value, Byte[] pattern)
{
if (value == null)
throw new ArgumentNullException("value");
if (pattern == null)
throw new ArgumentNullException("pattern");
Int64 valueLength = value.LongLength;
Int64 patternLength = pattern.LongLength;
if ((valueLength == 0) || (patternLength == 0) || (patternLength > valueLength))
return (new List<Int64>());
Int64[] badCharacters = new Int64[256];
for (Int64 i = 0; i < 256; ++i)
badCharacters[i] = patternLength;
Int64 lastPatternByte = patternLength - 1;
for (Int64 i = 0; i < lastPatternByte; ++i)
badCharacters[pattern[i]] = lastPatternByte - i;
// Beginning
Int64 index = 0;
List<Int64> indexes = new List<Int64>();
while (index <= (valueLength - patternLength))
{
for (Int64 i = lastPatternByte; value[(index + i)] == pattern[i]; --i)
{
if (i == 0)
indexes.Add(index);
}
index += badCharacters[value[(index + lastPatternByte)]];
}
return indexes;
}
Vielen Dank für diesen Code-Schnipsel, war nützlich für mich! –