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

本文介绍了strings.h头文件中的index和rindex函数,详细解释了它们如何查找字符串中特定字符的位置,并通过示例展示了使用方法。同时,文章还探讨了strings.h与string.h的区别及其在现代标准中的地位。

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

函数定义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

相关函数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. */
所以,一般使用前者就可以了


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值