天天看點

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

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

繼續閱讀