c语言字符串匹配函数index,C语言(函数)学习之index、rindex
函數定義:char *index(const char *s, int c);
頭文件:??? #include strings.h
函數說明:index()用來找出參數s 字符串中第一個出現的參數c 地址,然后將該字符出現的地址返回。字符串結束字符(NULL)也視為字符串一部分。
返回值:如果找到指定的字符則返回該字符所在地址,否則返回NULL
程序舉例:
#include
#include
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
#include
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 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. */
所以,一般使用前者就可以了。
總結
以上是生活随笔為你收集整理的c语言字符串匹配函数index,C语言(函数)学习之index、rindex的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: excel支持python吗_没有 Py
- 下一篇: 查看文件二进制编码_小白也能学会系列:用