zoukankan      html  css  js  c++  java
  • C语言(函数)学习之index、rindex

    一、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. */

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

  • 相关阅读:
    由数字三角形问题理解动态规划
    堆排序
    清理oracle数据库空间
    十个常用破解网络密码的方法
    说说windows下64位程序和32位程序
    sql server使用第二记
    手机通讯录PK
    sql server 初级实践记
    You and your research ( Richard Hamming) P5
    TED
  • 原文地址:https://www.cnblogs.com/liwei0526vip/p/4873112.html
Copyright © 2011-2022 走看看