C # byte [] Search

Source: Internet
Author: User

It is also relatively simple to search for the location where pattern appears in the byte array of data. Of course, this function can be expanded here, for example, to ignore case sensitivity and prevent exceptions.


Public static List <int> indexOf (byte [] data, byte [] pattern)
{
List <int> matchedPos = new List <int> ();

If (data. Length = 0 | data. Length <pattern. Length) return matchedPos;

Int end = data. Length-pattern. Length;
Bool matched = false;

For (int I = 0; I <= end; I ++)
{
For (int j = 0; j <pattern. Length |! (Matched = (j = pattern. Length); j ++)
{
If (data [I + j]! = Pattern [j]) break;
}
If (matched)
{
Matched = false;
MatchedPos. Add (I );
}
}
Return matchedPos;
}

The returned result is a List <int>. If the returned value is 0, the search fails.

Pay attention to the usage of the inside for (;). Generally, when the end is determined, the corresponding Boolean value is considered correct and the bypass of "|" is considered, that is, the right statement is executed only when "|" is False on the left side of the for statement on the inner side. Therefore, I reset the Boolean value in the right statement, then, determine whether the location matches.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.