我有一个看起来像这样的字符串:
"show net\r\r\nSSid=roving1\r\nChan=1\r\nAssoc=FAIL\r\nRate=12, 24Mb\r\nAuth=FAIL\r\nMode=NONE\r\nDHCP=FAIL\r\nBoot=0\r\nTime=OK\r\nLinks=0\r\n<4.00> "
这是我从外围设备接收到的数据,我想在其中扫描字符串“Auth=FAIL”。我正在使用以下命令查询它:
res = strstr(uart_rd, "Auth=FAIL");
然而,它返回值 0。但是如果我简单地发出命令:
res = strstr("nnAuth=FAILn", "Auth=FAIL");
它返回一个值。当它尝试搜索我的字符数组 uart_rd 时可能出了什么问题?
编辑:
看起来问题出在我为在将新数据放入数组之前清除数组所做的内存设置。我使用命令用 0 填充它:
memset(uart_rd,0,sizeof(uart_rd));
而我现在将其更改为
memset(uart_rd,"",sizeof(uart_rd));
这一切似乎都在起作用。不过,感谢您帮助诊断我的问题出在哪里!
最佳答案
嗯,这段代码
char uart_rd[] = "show net\r\r\nSSid=roving1\r\nChan=1\r\nAssoc=FAIL\r\nRate=12, 24Mb\r\nAuth=FAIL\r\nMode=NONE\r\nDHCP=FAIL\r\nBoot=0\r\nTime=OK\r\nLinks=0\r\n<4.00> ";
char *res;
res = strstr(uart_rd, "Auth=FAIL");
printf("%s", res);
给出这个输出:
Auth=FAIL
Mode=NONE
DHCP=FAIL
Boot=0
Time=OK
Links=0
<4.00>
所以你最好检查你的字符串声明。
关于c - 在 C 中搜索 char 数组中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21016182/