strchr, strrchr函式實現——string.h庫函式
阿新 • • 發佈:2018-12-31
函式實現:
資訊來自RHEL,man page:
STRCHR(3) Linux Programmer's Manual STRCHR(3)
NAME
strchr, strrchr, strchrnul - locate character in string
SYNOPSIS
#include <string.h>
char *strchr(const char *s, int c);
char *strrchr(const char *s, int c);
#define _GNU_SOURCE /* See feature_test_macros(7) */
#include <string.h>
char *strchrnul(const char *s, int c);
DESCRIPTION
The strchr() function returns a pointer to the first occurrence of the character c in the string s.
The strrchr() function returns a pointer to the last occurrence of the character c in the string s.
The strchrnul() function is like strchr() except that if c is not found in s, then it returns a pointer to the
null byte at the end of s, rather than NULL.
Here "character" means "byte"; these functions do not work with wide or multibyte characters.
RETURN VALUE
The strchr() and strrchr() functions return a pointer to the matched character or NULL if the character is not
found. The terminating null byte is considered part of the string, so that if c is specified as '\0', these
functions return a pointer to the terminator.
The strchrnul() function returns a pointer to the matched character, or a pointer to the null byte at the end of s (i.e., s+strlen(s)) if the character is not found.
VERSIONS
strchrnul() first appeared in glibc in version 2.1.1.
CONFORMING TO
strchr() and strrchr() are in SVr4, 4.3BSD, C89, C99. strchrnul() is a GNU extension.
strchr()函式實現:
0.函式原型:
#include <string.h>
char *strchr(const char *s, int c);
1.引數:
1.s:指定字串指標。
2.c:欲查詢字元’c’。
2.返回值:
如果字串s中:
->
含有'c'
字元,那麼返指向回字符'c'第一次
出現位置的指標
。
->如果沒有
,返回NULL。
3.功能描述:
strchr函式在指定字串s中查詢字元’c’,並返回指向該字元在字串中第一次出現位置的指標。沒找到則返回NULL。
4.實現:
char *my_strchr(const char *s, int c)
{
char *s_func = (char *)s;
//引數判斷
if(NULL == s_func){
return NULL;
}
//具體實現
while(*s_func && *s_func != c){
++s_func;
}
return (s_func ? s_func : NULL);
}
strrchr()函式實現:
0.函式原型:
#include <string.h>
char *strrchr(const char *s, int c);
1.引數:
同strchr函式引數。
2.返回值:
如果字串s中(區別與strchr函式的是,strrchr函式查詢的是c最後一次出現的位置):
->
含有'c'
字元,那麼返指向回字符'c'最後一次
出現位置的指標
。
->如果沒有
,返回NULL。。
3.功能描述:
strrchr函式參照strchr函式功能,區別在於該函式查詢c在字串中最後一次出現的位置。
4.實現:
實現一:
char *my_strrchr1(const char *s, int c)
{
char *s_func = (char *)s;
char *temp = NULL;
//引數判斷
if(NULL == s_func){
return NULL;
}
//temp找尾,s_func截頭
temp = s_func; //先將temp指向s
while(*temp){ //將temp指向s末尾
++temp;
}
while(temp != s_func && *temp != c){ //再讓temp指標往回跑,邊跑遍判斷是不是找到c
--temp;
}
//如果temp又回到了s的開頭,說明沒找到,返回NULL,否則返回temp
return (temp != s_func ? temp : NULL);
}
實現二:
char *my_strrchr2(const char *s, int c)
{
char *s_func = (char *)s;
char *result = NULL ;
//引數判斷
if(NULL == s_func){
return NULL;
}
//s_func從前往後找,result記錄最後一次指標
while(*s_func){ //s_func不指向空時迴圈判斷
if(*s_func == c){ //如果s_func指向c字元
result = s_func; //將當前位置記錄到result中
}
++s_func;
}
return (result ? result : NULL);
}
=============文章結束==============
小菜總結,如有不當,歡迎批評!