A more elegant way to search for a pattern in this uint8 array

I use the C language in the embedded system. I have this uint8 array.

static uint8_t data_array[20]; 

The contents of data_array terminates with '\n' .

I want to check if the first 3 bytes are "ABC". This is how I do it.

 if (data_array[0]=='A' && data_array[1]=='B' && data_array[2]=='C') { printf("pattern found\n"); } 

Are there more elegant ways to detect a pattern? My method can be cumbersome if the pattern consists of 10 bytes.

+5
source share
4 answers

Just use a loop:

 static uint8_t data_array[20] = "ABC"; static uint8_t s[4] = "ABC"; static uint8_t length = 3; uint8_t bool = 1; for (int i = 0; i < length; i++) { if (s[i] != data_array[i]) { bool = 0; break; } } if (bool) { printf("pattern found\n"); } 

Live code here

0
source

What about strncmp() ?

 static uint8_t data_array[20]; if(strncmp(data_array, "ABC", 3) == 0) { printf("pattern found\n"); } 
0
source
 char small='a' ,big='A'; int i=0; char arr[10]; //To check for(i; i<10 ; i++) { if(arr[i]==small || arr[i]==big) { //what you want to do } small++; big++; } 
-1
source

You can use macros to generate code similar to yours:

 #include <stdio.h> #define TEST_FIRST_1(arr, c0) ((c0) == *(arr)) #define TEST_FIRST_2(arr, c0, ...) (TEST_FIRST_1(arr, c0) && TEST_FIRST_1((arr) + 1, __VA_ARGS__)) #define TEST_FIRST_3(arr, c0, ...) (TEST_FIRST_1(arr, c0) && TEST_FIRST_2((arr) + 1, __VA_ARGS__)) #define TEST_FIRST_4(arr, c0, ...) (TEST_FIRST_1(arr, c0) && TEST_FIRST_3((arr) + 1, __VA_ARGS__)) #define TEST_FIRST_5(arr, c0, ...) (TEST_FIRST_1(arr, c0) && TEST_FIRST_4((arr) + 1, __VA_ARGS__)) /* continue, if need */ static unsigned char data[30] = { 1,2,3,4,5,6,7,8,9,10,11,12,13, }; int main(int argc, char **argv) { /* true cases */ printf("%d\n", TEST_FIRST_1(data, 1)); printf("%d\n", TEST_FIRST_2(data, 1, 2)); printf("%d\n", TEST_FIRST_3(data, 1, 2, 3)); printf("%d\n", TEST_FIRST_4(data, 1, 2, 3, 4)); printf("%d\n", TEST_FIRST_5(data, 1, 2, 3, 4, 5)); /* false cases */ printf("%d\n", TEST_FIRST_5(data, 0, 0, 0, 0, 0)); printf("%d\n", TEST_FIRST_4(data, 0, 0, 0, 0)); printf("%d\n", TEST_FIRST_3(data, 0, 0, 0)); return 0; } 

It may seem that it is not clean at first glance, but in any case does not lead to the creation of additional string literals for comparing patterns.

-1
source

All Articles