#include <string.h>
void *memchr( const void *buffer, int ch, size_t count );
函数在 buffer 指向的数组的 count 个字符的字符串里查找 ch 首次出现的位置。返回一个指针,指向 ch 在字符串中首次出现的位置,如果 ch 没有在字符串中找到,返回 NULL。
(1)使用 memchr 函数查找字符数组中是否包含“X”字符,如下:
#include <stdio.h>
#include <string.h>
int main() {
char names[] = "Alan Bob Chris X Dave";
if( memchr(names,'X',strlen(names)) == NULL ) {
printf( "Didn't find an X\n" );
} else {
printf( "Found an X\n" );
}
return 0;
}输出结果:
Found an X
(2)使用 memchr 函数搜索字符“r”在字符数组中首次出现的位置,如下:
#include <stdio.h>
#include <string.h>
int main() {
char str[17];
char *ptr;
strcpy(str, "This is a string");
ptr = memchr(str, 'r', strlen(str));
if (ptr) {
printf("The character 'r' is at position: %d\n", ptr - str);
} else {
printf("The character was not found\n");
}
return 0;
}输出结果:
The character 'r' is at position: 12