对于初学者,您的字符数组不包含字符串。
char byte_arr[5] = "abc00";
因此,要确定字符“0”是否存在于数组中,您必须使用其大小遍历它的元素。
在这种情况下,您可以使用循环,例如 while 循环
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 %zu\n, 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 %zu\n, c, ( size_t )( p - byte_arr ) );