Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to find does Span<T> contains other Span<T> in the same order

I want to check does a Span<T> contains a Span<T> elements in the same order.

Span<byte> buffer = stackalloc byte[] { 1, 6, 2, 5, 3, 4 };

Span<byte> needle1 = stackalloc byte[] { 2, 5, 3 }; // this one is contained in buffer in the same order
Span<byte> needle2 = stackalloc byte[] { 2, 5, 4 }; // this one is not contained in buffer in the same order

I’m aware I can use Span<T>.Contains() that takes only one element as parameter to find the first element of needle in the buffer and then manually compare next elements one by one, but this seems highly suboptimal and tedious process.

Span<T>.Overlaps() is not the answer here, because needle is not stored in the same memory address as buffer. I’d like to avoid LINQ, because of performance reasons. Is there additional method in the standard library I am missing?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use MemoryExtensions.IndexOf<T>(this Span<T> span, ReadOnlySpan<T> value):

Searches for the specified sequence and returns the index of its first occurrence. Values are compared using IEquatable{T}.Equals(T).

Returns Int32
The index of the occurrence of the value in the span. If not found, returns -1.

var contains1 = buffer.IndexOf(needle1) >= 0;
var contains2 = buffer.IndexOf(needle2) >= 0;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading