char *strchr(const char *s, int c); char *strrchr(const char *s, int c); |
#include <string.h> |
函數說明: strchr:查找字符串s中第一次出現字符c的位置,並返回該字符以及該字符之後所有的字符 strrchr:查找字符串S中最後一次出現字符c的位置,同時返回該字符以及字符以後的所有字符。 兩個函數如果未找到字符則返回NULL 注意:此處c爲int類型。如果該輸入爲數字則採用ASCII碼進行字符的匹配 |
|
代碼示例: 2 #include<string.h> 3 int main() 4 { 5 const char *buf1="hfah/garuhg/ghuag"; 6 const char *buf2="124254365465"; 7 int c='/'; 8 printf("s1:%s\t s2:%s\t %c\n",buf1,buf2,c); 9 printf("buf1:strchr():%s\n",strchr(buf1,c)); 10 printf("buf1:strrchr():%s\n",strrchr(buf1,c)); 11 printf("buf2:strchr():%s\n",strchr(buf2,c)); 12 printf("buf2:strrchr():%s\n",strrchr(buf2,c)); 13 return 0; 14 15 } |
|
運行結果: |
|
進一步分析: 在做字符串處理的時候,有時我們可能需要使用/字符後面的內容,可以使用一個指針指向返回的字符串,指針自加指向下一個字符。 代碼: 1 #include<stdio.h> 2 #include<string.h> 3 int main() 4 { 5 const char *buf1="hfah/garuhg/ghuag"; 6 const char *buf2="124254365465"; 7 char *p; 8 int c='/'; 9 printf("s1:%s\t s2:%s\t %c\n",buf1,buf2,c); 10 printf("buf1:strchr():%s\n",strchr(buf1,c)); 11 printf("buf1:strrchr():%s\n",strrchr(buf1,c)); 12 printf("buf2:strchr():%s\n",strchr(buf2,c)); 13 printf("buf2:strrchr():%s\n",strrchr(buf2,c)); 14 p=strrchr(buf1,c); 15 p++; 16 printf("%s\n",p); 17 return 0; 18 19 } 結果: |