for (int i = 0; i < fs.Length; i++) { if (fs[i] == 64) { if (fs[i + 1] == 115) { if (fs[i + 2] == 46) { if (fs[i + 3] == 119) { if (fs[i + 4] == 104) { if (fs[i + 5] == 97) { if (fs[i + 6] == 116) { if (fs[i + 7] == 115) { if (fs[i + 8] == 97) { byte[] noom = { fs[i - 11], fs[i - 10], fs[i - 9], fs[i - 8], fs[i - 7], fs[i - 6], fs[i - 5], fs[i - 4], fs[i - 3], fs[i - 2], fs[i - 1] }; string str = Encoding.UTF8.GetString(noom, 0, noom.Length); if (Convert.ToInt64(str) > 0) { numbers.Add(str); } } } } } } } } } } } 

Now I use something like this. Inconvenient

  • 2
    SequenceEqual ? - VladD
  • @VladD, As I understand it - this function compares the sequences for equality exactly, and not for inclusion - Mart
  • one
    Well, add more Skip and Take to the original sequence, yes, the same cycle in i . - VladD
  • 2
    and who prevents to correct the code for something like var need = true; var values = new int[]{64,115, 46,119,..};for(int j=0;j<9;j++){need=need&fs[i + j] == values[j]} var need = true; var values = new int[]{64,115, 46,119,..};for(int j=0;j<9;j++){need=need&fs[i + j] == values[j]} and then if need, then .. - Monomax
  • one
    @Mart did I understand correctly that it’s not exactly writing the long code that you are not satisfied with, and not the time of its execution? - Monomax

1 answer 1

I think you need something like this:

 var pattern = new byte[] { 64, 115, 46, 119, 104, 97, 116, 115, 97 }; const int patternOffset = 11; for (int i = patternOffset; i < fs.Length - pattern.Length; i++) { if (!fs.Skip(i).Take(pattern.Length).SequenceEqual(pattern)) continue; var numBytes = fs.Skip(i - patternOffset).Take(patternOffset); string str = Encoding.UTF8.GetString(numBytes, 0, numBytes.Length); if (long.TryParse(str, out var num)) numbers.Add(num); } 

Pay attention to the starting and ending indices in the for loop: without this amendment, you risk flying out of range.


As @ AndreyNOP suggests in the comments, you can use more elegant

 new ArraySegment(fs, i, pattern.Length).SequenceEqual(pattern) 

and

 var numBytes = new ArraySegment(fs, i - patternOffset, patternOffset); 
  • 2
    Instead of the .Skip().Take() combination, you can use the ArraySegment - Andrey NOP
  • @AndreyNOP: Cool, did not know! Thank! - VladD
  • You could also use Array.IndexOf () in the starting condition in a loop: int i = Array.IndexOf (fs [0]); and in the loop itself, instead of iterating over all i if the SequenceEqual does not match, do i = Array.Skip (i) .IndexOf (fs [0]); continue; - Alexander
  • @Alexander: If you develop your idea, you can use any of the substring search algorithms. Yes, even KMP . - VladD