当前位置: C语言 -- 标准库 -- <string.h> -- memchr

memchr函数


概要:
#include <string.h>
void *memchr(const void *s, int c, size_t n);

描述:

该函数搜索参数c指定的字符(转换为unsigned char类型。)在参数s指向对象的初始n个字符中第一次出现的位置。

实现就像按顺序读取字符,遇到匹配字符立即停止。


参数:
const void *s

指向对象的指针。

int c

要搜索的字符,会转换成unsigned char类型。

size_t n

搜索的最大字符数。


返回值:

如果参数s指向对象不存在要搜索字符,函数返回空指针;否则函数返回指向第一个匹配成功的字符的指针。


范例:
1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
12 
13 
14 
15 
16 
17 
18 
19 
20 
21 
/*函数memchr范例*/

#include <stdio.h>
#include <string.h>

int main(void)
{
    const char str[] = "There is no rose without a thorn.";
    const char *ptr = str;
    char ch = 'o';

    /*输出字符串中所有字母o的位置。*/
    puts("The position of character o: ");
    while(ptr = memchr(ptr, ch, strlen(ptr)))
    {
        printf("%td ", (++ptr-str));
    }
    
    return 0;
}


输出:

The position of character o:

11 14 22 30


相关内容:
strchr 搜索指定字符在字符串中第一次出现位置的函数。
strcspn 计算最大初始片段长度的函数。
strpbrk 搜索字符在字符串中第一次出现位置的函数。
strrchr 搜索指定字符在字符串中最后一次出现位置的函数。
strspn 计算最大初始片段长度的函数。
strstr 搜索子字符串在字符串中第一次出现位置的函数。
strtok 拆分字符串的函数。