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

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM