C语言字符篇(四)字符串查找函数

 
#include <string.h>  
char *strchr(const char *s, int c);
 
The strchr() function returns a pointer to the first occurrence of the character c in the string s.

 

char *strrchr(const char *s, int c);
The strrchr() function returns a pointer to the last occurrence of the character c in the string s.
size_t strspn(const char *s, const char *accept); The strspn() function calculates the length (in bytes) of the initial segment of s which consists entirely of bytes in accept.
size_t strcspn(const char *s, const char *reject); The strcspn() function calculates the length of the initial segment of s which consists entirely of bytes not in reject.
char *strpbrk(const char *s, const char *accept); The strpbrk() function returns a pointer to the byte in s that matches one of the bytes in accept, or NULL if no such byte is found.
char *strstr(const char *haystack, const char *needle); These functions return a pointer to the beginning of the located substring, or NULL if the substring is not found.
 
 
 
char *strchr(const char *s, int c);:    记录c第一次在s出现的位置,并记录当前指针
char *strrchr(const char *s, int c);:   记录c最后一次出现在s的指针,并记录当前指针位置
-------------------------------------------------------
int main(int argc, char **argv) {


    const char *buf="hello strchr";
    char *p1;
    char *p2;
    p1=strchr(buf,'l'); //记录字符l第一次出现的位置,并范围第一次出现该字符的指针
    printf("%s\n",p1);  //llo strchr


    p2=strrchr(buf,'l');//记录字符最后一次出现的位置,并范围第一次出现该字符的指针
    printf("%s\n",p2);  //lo strchr


}

 

 

size_t strspn(const char *s, const char *accept);:
size_t strcspn(const char *s, const char *reject);:
-------------------------------------------------------
int main(int argc, char **argv) {


    const char *buf="hello world";
    int len;


    /*在buf中寻找buf2中的任意字符,也就是说,在buf中,如果碰到buf2中的任意字符,就结束寻找,并记录之前不相等部分的字符数*/
    /*比如,在buf中有个空格是buf2可以匹配到的,在空格之前有5个字节是不匹配的,所以返回值为5*/
    /*统计不同的数,直到出现了buf2中存在的字符*/
    len=strcspn(buf,"\t\n,.?! ");   //
    printf("scpn:%d\n",len);


    /*统计相同的数,直到出现了buf2里面不存在的字符*/
    len=strspn(buf,"abcdefghijklmn");   //hell 都在buf2中出现过,所以开始统计,到 o,buf2中没有,返回到停止之前统计的字符数
    printf("spn:%d\n",len);


}

 

 
char *strpbrk(const char *s, const char *accept);:s中只要出现匹配的任意字符,就返回相应的指针位置
-------------------------------------------------------
匹配任意字符出现就返回
          int main(int argc, char **argv) {
                const char *buf="hello,kmist";


                char *p;


                p = strpbrk(buf,"abcdefg");
                printf("%s\n",p);   //ello,kmist
            }

 

 

char *strstr(const char *haystack, const char *needle);:
-------------------------------------------------------
匹配到全部字符串返回指针
            int main(int argc, char **argv) {


                const char *buf="hello,kmist";


                char *p;


                p = strstr(buf,"kmi");
                printf("%s\n",p);   //kmist ,如果没有就返回null
            }

 

posted @ 2018-12-10 23:10  kmist  阅读(19190)  评论(0编辑  收藏  举报