原型:
C库string.h中的strchr函数
描述:
C 库函数 char *strchr(const char *str, int c) 在参数 str 所指向的字符串中搜索第一次出现字符 c(一个无符号字符)的位置。
参数:
str:要被检索的C字符串。
c:在str中要搜索的字符。
返回值:
该函数返回在字符串 str 中第一次出现字符 c 的位置,如果未找到该字符则返回 NULL。
模拟实现strchr:
char *strchr(const char *str, int c)
{
assert(NULL != str);
while (*str && (*str != (char)c))
++str;
if ((char)c == *str) //包含了*str和c都为0的情况。
return (char *)str;
return NULL;
}
原型:
C库string.h中的strrchr函数
描述:
C 库函数 char *strrchr(const char *str, int c) 在参数 str 所指向的字符串中搜索最后一次出现字符 c(一个无符号字符)的位置。
参数:
str:要被检索的C字符串。
c:要搜索的字符。以 int 形式传递,但是最终会转换回 char 形式。
返回值:
该函数返回在字符串 str 中最后一次出现字符 c 的位置,如果未找到该字符则返回 NULL。
模拟实现strrchr:
第一种方法:从头往后找
char *my_strrchr(const char* str, int c)
{
char *ret = NULL;
assert(NULL != str);
while (*str)
if (*str == (char)c) //如果存在,ret保存地址
ret = (char *)str; //强制转换指针类型,赋给ret
else
++str;
if ((char)c == *str) //考虑str第一个字符为'\0'的情况
ret = (char *)str; //强制转换指针类型,赋给ret
return ret;
}
第二种方法:从后往前找
char *my_strrchr(const char* str, int c)
{
char *ret = (char *)str;//强制转换指针类型,赋给ret
while (*str) //指向原str字符串最后一位
++str;
while (*str != (char)c && (str >= ret))
--str;
if (str >= ret)
return (char *)str;//强制转换指针类型,返回。
return NULL;
}
原型:
C库string.h中的memchr函数
描述:
C 库函数 void *memchr(const void *str, int c, size_t n) 在参数 str 所指向的字符串的前 n 个字节中搜索第一次出现字符c(一个无符号字符)的位置。
参数:
str:指向要执行搜索的内存块。
c:以 int 形式传递的值,但是函数在每次字节搜索时是使用该值的无符号字符形式。
n:要被分析的字节数。
返回值:
该函数返回一个指向匹配字节的指针,如果在给定的内存区域未出现字符,则返回 NULL。
模拟实现memchr:
void *my_memchr(const void *str, int c, size_t n)
{
char *pstr = (char *)str;
assert(NULL != str);
while (n--)
if ((char)c == *pstr)
return pstr;
else
++pstr;
return NULL;
}