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
            }

 


免責聲明!

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



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