C语言:字符串中查找指定字符——strchr()和strrchr()

参考文章连接:

1.http://c.biancheng.net/cpp/html/161.html

2.http://c.biancheng.net/cpp/html/172.html

https://blog.csdn.net/luna_zhan/article/details/80433351

1.头文件:#include <string.h>

strchr() 用来查找某字符在字符串中首次出现的位置,其原型为:
    char * strchr (const char *str, int c);
【参数】str 为要查找的字符串,c 为要查找的字符。
strchr() 将会找出 str 字符串中第一次出现的字符 c 的地址,然后将该地址返回。
注意:字符串 str 的结束标志 NUL 也会被纳入检索范围,所以 str 的组后一个字符也可以被定位。
【返回值】如果找到指定的字符则返回该字符所在地址,否则返回 NULL。
返回的地址是字符串在内存中随机分配的地址再加上你所搜索的字符在字符串位置。设字符在字符串中首次出现的位置为 i,那么返回的地址可以理解为 str + i。
提示:如果希望查找某字符在字符串中最后一次出现的位置,可以使用 strrchr() 函数。
【实例】查找字符5首次出现的位置。

 
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. int main(){
  6.     char *s = "0123456789012345678901234567890";
  7.     char *p;
  8.     p = strchr(s, '5');
  9. printf("%ld\n", s);
  10.     printf("%ld\n", p);
  11.  
  12. system("pause");
  13.     return 0;
  14. }

输出结果:
12016464

12016469

2.头文件:#include <string.h>

strrchr() 函数用于查找某字符在字符串中最后一次出现的位置,其原型为:
    char * strrchr(const char *str, int c);

【参数】str 为要查找的字符串,c 为要查找的字符。

strrchr() 将会找出 str 字符串中最后一次出现的字符 c 的地址,然后将该地址返回。

注意:字符串 str 的结束标志 NUL 也会被纳入检索范围,所以 str 的组后一个字符也可以被定位。

【返回值】如果找到就返回该字符最后一次出现的位置,否则返回 NULL。

返回的地址是字符串在内存中随机分配的地址再加上你所搜索的字符在字符串位置。设字符在字符串中首次出现的位置为 i,那么返回的地址可以理解为 str + i。

提示:如果希望查找某字符在字符串中第一次出现的位置,可以使用 strchr() 函数。

实例:查找字符5最后一次出现的位置。

 
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. int main(){
  6.     char *s = "0123456789012345678901234567890";
  7.     char *p;
  8.     p = strrchr(s, '5');
  9.     printf("%ld\n", s);
  10.     printf("%ld\n", p);
  11.  
  12.     system("pause");
  13.     return 0;
  14. }

执行结果:
12999504
12999529

猜你喜欢

转载自blog.csdn.net/qq_34272143/article/details/82018672