C标准库string.h源码五:strchr/strrchr/strstr

 char *strchr(const char *s, int c); //返回一个字符指针,它指向c在s中首次出现的位置,如果未找到,返回NULL
 char *strrchr(const char *s, int c);//返回一个字符指针,它指向c在s中最后出现的位置,如果未找到,返回NULL
 char *strchrnul(const char *s, int c);//若c在s中,同strchr,否则返回指向字符串末尾的‘\0’的指针,而不是NULL
 char *strstr(const char *str, const char *sub);//查找子串strstr:在字符串str中查找子串sub,若找到,则指针返回sub第一次出现在str中的位置,否则返回NULL

/*
char *strchr(string, chr) - search a string for a character

Purpose:
       Searches a string for a given character, which may be the
       null character '\0'.
*/
char *strchr (const char *string, int chr)
{
    while (*string && *string != chr)
        string++;
    if (*string == chr)
        return(string);
    return((char *)0);
}

​​
/*
       returns a pointer to the last occurrence of ch in the given
       string. returns NULL if ch does not occurr in the string
*/

char *strrchr (const char *string, int ch)
{
    char *start = string;
    while (*string++)
        ;
    while (--string != start && *string != ch)
        ;
    if (*string == ch)
        return(string);
    return(NULL);
}

​​
​

char *strchrnul (const char *string, int chr)
{
    while (*string && *string != chr)
        string++;
    return(string); 
}

​
​​
/* Find the last occurrence of C in S.  */
char *strrchr (const char *s, int c)
{
  register const char *found, *p;

  c = (unsigned char) c;

  /* Since strchr is fast, we use it rather than the obvious loop.  */

  if (c == '\0')
    return strchr (s, '\0');

  found = NULL;
  while ((p = strchr (s, c)) != NULL)
    {
      found = p;
      s = p + 1;
    }

  return (char *) found;
}
 
​
/***
*char *strstr(string1, string2) - search for string2 in string1
*
*Purpose:
*       finds the first occurrence of string2 in string1
*
*Entry:
*       char *string1 - string to search in
*       char *string2 - string to search for
*
*Exit:
*       returns a pointer to the first occurrence of string2 in
*       string1, or NULL if string2 does not occur in string1
*******************************************************************************/
char * strstr (const char * str1,const char * str2)
{
        char *cp = (char *) str1;
        char *s1, *s2;

        if ( *str2 == '\0' )
            return((char *)str1);

        while (*cp)
        {
                s1 = cp;
                s2 = (char *) str2;

                while ( *s1 && *s2 && (*s1 == *s2) )
                        s1++, s2++;

                if (*s2 == '\0')
                        return(cp);

                cp++;
        }

        return(NULL);
}
​

​

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值