模拟实现strchr.strrchr

来源:互联网 发布:景观格局数据单位 编辑:程序博客网 时间:2024/06/05 00:22

模拟实现strchr
strchr函数返回要查找字符子字符串中第一次出现的地址

#include <stdio.h>#include <stdlib.h>#include <assert.h>char *my_strchr(const char *string, int c){    assert(string);    while (*string != '\0')    {        if (*string == c)            return string;        string++;    }  return NULL;}int main(){    char a[] = "abcabc";    char ch = 'a';    printf("%s\n", my_strchr(a, ch));    system("pause");    return 0;}

模拟实现strrchr
strrchr函数返回要查找字符子字符串中最后一次出现的地址,所以可以从后向前考虑,找字符第一次出现在字符串的地址。

#include <stdio.h>#include <stdlib.h>#include <assert.h>char *my_strchr(const char *string, int c){    assert(string);    while (*string != '\0')    {        string++;    }    while (*(--string))    {        if (*string == c)            return string;    }}int main(){    char a[] = "abcabc";    char ch = 'a';    printf("%s\n", my_strchr(a, ch));    system("pause");    return 0;}
0 0
原创粉丝点击