c语言字符串匹配函数index,C语言(函数)学习之index、rindex
函數(shù)定義:char *index(const char *s, int c);
頭文件:??? #include strings.h
函數(shù)說明:index()用來找出參數(shù)s 字符串中第一個出現(xiàn)的參數(shù)c 地址,然后將該字符出現(xiàn)的地址返回。字符串結(jié)束字符(NULL)也視為字符串一部分。
返回值:如果找到指定的字符則返回該字符所在地址,否則返回NULL
程序舉例:
#include
#include
int main()
{
char *s = "abcdef123456abcdef";
char *p = NULL;
p = index(s, 'b');
printf("%s\n", p);
return 0;
}
執(zhí)行結(jié)果:
dzlab:~/test/test# ./a.out
bcdef123456abcdef
相關(guān)函數(shù):char *rindex(const char *s, int c);
函數(shù)說明:rindex()用來找出參數(shù)s 字符串中最后一個出現(xiàn)的參數(shù)c 地址,然后將該字符出現(xiàn)的地址返回。字符串結(jié)束字符(NULL)也視為字符串一部分。
程序舉例:
#include
#include
int main()
{
char *s = "abcdef123456abcdef";
char *p = NULL;
p = rindex(s, 'b');
printf("%s\n", p);
return 0;
}
執(zhí)行結(jié)果:
dzlab:~/test/test# ./a.out
bcdef
擴(kuò)展部分:
在查man手冊的時候,發(fā)現(xiàn)頭文件是strings.h,不是string.h,是不是手冊錯了,于是乎百度了一番,找到了具體描述結(jié)果:
strings.h頭文件是從BSD系UNIX系統(tǒng)繼承而來,里面定義了一些字符串函數(shù),如bzero等。這些函數(shù)曾經(jīng)是posix標(biāo)準(zhǔn)的一部分,但是在POSIX.1-2001標(biāo)準(zhǔn)里面,這些函數(shù)被標(biāo)記為了遺留函數(shù)而不推薦使用。在POSIX.1-2008標(biāo)準(zhǔn)里已經(jīng)沒有這些函數(shù)了,如下:
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)什么時候使用呢?打開這個頭文件,可以看見區(qū)別如下:
/* We don't need and should not read this file if 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. */
所以,一般使用前者就可以了。
總結(jié)
以上是生活随笔為你收集整理的c语言字符串匹配函数index,C语言(函数)学习之index、rindex的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: excel支持python吗_没有 Py
- 下一篇: 把百度网站设为首页_网站百度推广效果好不