C语言(函数)学习之index、rindex

本文详细介绍了C库中用于字符串操作的index和rindex函数,包括其函数定义、头文件引用、函数说明以及执行示例。文章还探讨了与之相关的字符串函数,并解释了strings.h头文件与string.h的区别,提供了正确的使用指南。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、index函数

函数定义

char *index(const char *s, int c);

头文件:    

#include strings.h

函数说明

index()用来找出参数s 字符串中第一个出现的参数c地址,然后将该字符出现的地址返回。字符串结束字符(NULL)也视为字符串一部分。

返回值

如果找到指定的字符则返回该字符所在地址,否则返回NULL

程序举例:

#include <stdio.h>
#include <strings.h>
int main()
{
    char *s = "abcdef123456abcdef";
    char *p = NULL;
    p = index(s, 'b');
    printf("%s\n", p); 
    return 0;
}

执行结果:

dzlab:~/test/test# ./a.out    
bcdef123456abcdef

二、rindex函数

相关函数

char *rindex(const char *s, int c);

函数说明

rindex()用来找出参数s 字符串中最后一个出现的参数c 地址,然后将该字符出现的地址返回。字符串结束字符(NULL)也视为字符串一部分。

程序举例

#include <stdio.h>
#include <strings.h>
int main()
{
        char *s = "abcdef123456abcdef";
        char *p = NULL;
        p = rindex(s, 'b');
        printf("%s\n", p);
        return 0;
}

执行结果:

dzlab:~/test/test# ./a.out
bcdef

三、扩展部分

在查man手册的时候,发现头文件是strings.h,不是string.h,是不是手册错了,于是乎百度了一番,找到了具体描述结果:

strings.h 头文件是从 BSD 系 UNIX 系统继承而来,里面定义了一些字符串函数,如 bzero 等。这些函数曾经是 posix 标准的一部分,但是在POSIX.1-2001 标准里面,这些函数被标记为了遗留函数而不推荐使用。在 POSIX.1-2008 标准里已经没有这些函数了,如下:

int bcmp(const void *, const void *, size_t);         /* 用memcmp替代 */
void bcopy(const void *, void *, size_t);             /* 用memcpy, memmove替代 */
void bzero(void *, size_t);                           /* 用memset替代 */
int ffs(int);                                         /* string.h 中有 */
char *index(const char *, int);                       /* 用strchr替代 */
char *rindex(const char *, int);                      /* 用strrchr替代 */
int strcasecmp(const char *, const char *);           /* string.h 中有 */
int strncasecmp(const char *, const char *, size_t);  /* string.h 中有 */

这两个头文件都在 linux 的 /usr/include 目录下面,后者比前者多了一个 s,一般使用以 string.h(没有s)的为主,那 strings.h(有s)什么时候使用呢?打开这个头文件,可以看见区别如下:

/* We don't need and should not read this file if <string.h> was already
read. The one exception being that if __USE_BSD isn't defined, then
these aren't defined in string.h, so we need to define them here. */

所以,一般使用前者就可以了

转载于:https://www.cnblogs.com/liwei0526vip/p/4873112.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值