我有一个strings
的byte array
。如何检查数组中的某个字节是否包含0?例如:
char byte_arr[5] = "abc00";
上面数组的最后两个字节包含0。如何在c
中检测
遵循的简单算法
count_zero = 0
for each element a, in byte_array
check if a is '0'
count_zero++
即使我们使这段代码编译(假设uint8
在某处定义)
uint8 byte_arr[5] = "abc00";
则该数组中没有字节(除了第5个字节)的值为零。字符'0'
的最后两个保留值取决于所使用的字符编码。
要检查数组中某个特定元素是否存在某个值,需要将其与该值进行比较
if(byte_arr[4] == '0') printf("Success!!!!n");
else printf("Failure!!!!n");
首先,您的字符数组不包含字符串。
char byte_arr[5] = "abc00";
因此,要确定字符'0'是否存在于数组中,您必须使用它的大小遍历它的元素。
在这种情况下,可以使用循环,例如while loop
size_t i = 0;
char c = '0';
while ( i < 5 && byte_arr[i] != c ) i++;
if ( i != 5 ) printf( "The character %c is present at position %zun, c, i );
如果您需要确定包含字符'0'
的所有元素的位置或对它们进行计数,则可以使用for循环。
#include <stdio.h>
int main(void)
{
enum { N = 5 };
char byte_arr[N] = "abc00";
char c = '0';
size_t count = 0;
for ( size_t i = 0; i < N; i++ )
{
if ( byte_arr[i] == c )
{
++count;
printf( "At the position %zu there is the character '%c'n", i, c );
}
}
printf( "There are %zu elements in the array that contains '%c'.n", count, c );
return 0;
}
程序输出为
At the position 3 there is the character '0'
At the position 4 there is the character '0'
There are 2 elements in the array that contains '0'.
如果你将数组声明为例如
char byte_arr[] = "abc00";
则数组将包含一个字符串。在这种情况下,您可以使用标准字符串函数strchr
来检查给定字符是否存在于字符串中。例如
#include <string.h>
//...
char byte_arr[] = "abc00";
char c = '0';
char *p = strchr( byte_arr, c );
if ( p != NULL ) printf( "The character %c is present at position %zun, c, ( size_t )( p - byte_arr ) );
在string.h
中有一个标准函数,如果任务只是确定是否存在:
if ( memchr(byte_arr, '0', sizeof byte_arr) )
printf("There was a zero.n");
你可以循环数组直到你到达终点或找到所需的字符:
int main(void) {
char byte_arr[5] = "abc00";
for (int i =0; i<5; ++i)
{
if(byte_arr[i]=='0'){
printf("Found!!");
break;
}
}
return 0;
}