c - 在此 uint8 数组中搜索模式的更优雅方式

标签 c

我在嵌入式系统中使用 C 语言。我有这个 uint8 数组。

static uint8_t data_array[20];

data_array 的内容以'\n' 结束。

我想检查前 3 个字节是否为“ABC”。我就是这样做的。

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

是否有更优雅的方法来检测模式?如果模式由 10 个字节组成,我的方法可能会很麻烦。

最佳答案

只需使用一个循环:

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

关于c - 在此 uint8 数组中搜索模式的更优雅方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38500353/

相关文章:

c,宏,位数的必要单位

c++ - 在 android 内核开发 linux 中使用蓝牙

c - 如何使 `make` 为文件夹中的每个 C 文件创建一个可执行文件?

c - 从中缀到后缀

c - 在 C 中的引号之间读取带有空格的用户输入字符串

c - 为什么我的程序输出整数而不是 float ?

c - getopt() 中的 optarg 始终为 null

c - 使用 sscanf 读取可选数字

c - 当输入的长度超过 C 字符串数组的大小时,有哪些选项可以处理它?

c++ - if 中的多个语句是否与多个 if 相同?