/*
函数名称: strrchr
函数原型:char *strrchr(const char *str, int c);
所属库: string.h
函数功能:查找一个字符c在另一个字符串str中末次出现的位置(也就是从str的右侧开始查找字符c首次出现的位置),
并返回从字符串中的这个位置起,一直到字符串结束的所有字符。如果未能找到指定字符,那么函数将返回NULL。
这个函数和strchr函数其实是差不多的,一个是从前往后,一个是从后往前而已。
*/
#include <stdio.h>
char *strrchr(const char *str, int c)
{
const char *p = str;
while(*p)
{
p++;
}
do
{
if (*p == (char)c)
{
return (char*)p;
}
}while(--p>=str)
return NULL;
}
int main(void)
{
char *string = "There are two rings";
char *ptr, c = 'r';
ptr = strrchr(string, c);
if (ptr)
printf("The character %c is at position: %s\n", c, ptr);
else
printf("The character was not found\n");
return 0;
}
//linux源码
#ifndef __HAVE_ARCH_STRRCHR
/**
* strrchr - Find the last occurrence of a character in a string
* @s: The string to be searched
* @c: The character to search for
*/
char *strrchr(const char *s, int c)
{
const char *p = s + strlen(s);
do {
if (*p == (char)c)
return (char *)p;
} while (--p >= s);
return NULL;
}
EXPORT_SYMBOL(strrchr);
#endif
/**
FUNCTION
<<strrchr>>---reverse search for character in string
INDEX
strrchr
ANSI_SYNOPSIS
#include <string.h>
char * strrchr(const char *<[string]>, int <[c]>);
TRAD_SYNOPSIS
#include <string.h>
char * strrchr(<[string]>, <[c]>);
char *<[string]>;
int *<[c]>;
DESCRIPTION
This function finds the last occurence of <[c]> (converted to
a char) in the string pointed to by <[string]> (including the
terminating null character).
RETURNS
Returns a pointer to the located character, or a null pointer
if <[c]> does not occur in <[string]>.
PORTABILITY
<<strrchr>> is ANSI C.
<<strrchr>> requires no supporting OS subroutines.
QUICKREF
strrchr ansi pure
*/
#include <string.h>
char *
_DEFUN (strrchr, (s, i),
_CONST char *s _AND
int i)
{
_CONST char *last = NULL;
if (i)
{
while ((s=strchr(s, i)))
{
last = s;
s++;
}
}
else
{
last = strchr(s, i);
}
return (char *) last;
}
strrchr() 函数的分析
函数原型:extern char * strrchr (const char *s, int c)
参数说明:s为一个字符串的指针,c为一个待查找字符。
所在库名:#include <string.h>
函数功能:查找在s字符串中最后一次出现字符c的位置。
返回说明:如果str 中存在字符ch,返回出现ch的位置的指针;否则返回NULL。
说明:
str
必要参数。指定需要进行搜索的字符串(字符串指针)
c
必要参数。指定需要查找的字符对象。如果是 一个数字,那么他将搜索与这个数字对应的ASCII值相匹配的字符
strrchr()函数源码:
/* 查找在s字符串中最后一次出现字符c的位置 */
char * strrchr (const char *s, int c)
{
register const char *found, *p;
c = (unsigned char) c;
//如果查找的字符是结束符,直接用strchr 函数返回结束符号的位置。
if (c == '\0')
return strchr (s, '\0');
//返回值(查找的字符地址)赋初值,很重要。
found = NULL;
//从当前字符串超找字符c,并将返回指针赋给p,如果p不等于NULL,则执行循环。
//如果p等于NULL,说明已查找整个字符串,退出循环。
while ( (p = strchr (s, c)) != NULL )
{
//暂存查找到的字符地址。
found = p;
//截取已经查找过的字符串(将返回地址p的下一个字符地址作为字符串开头)。
s = p + 1;
}
//如果没有找到字符,则不会执行循环,found返回初值NULL。
//如果找到字符,返回p赋给found的指针地址。
return (char *) found;
}