C语言strchr函数

strchr函数原型:extern char *strchr(const char *s,char c);查找字符串s中首次出现字符c的位置。

C语言

char *strchr(const char* _Str,int _Val)
char *strchr(char* _Str,int _Ch)
头文件:#include <string.h>
功能:查找 字符串s中首次出现字符c的位置
说明:返回首次出现c的位置的 指针,返回的地址是被查找字符串指针开始的第一个与Val相同字符的指针,如果s中不存在c则返回 NULL
返回值:成功则返回要查找字符第一次出现的位置,失败返回NULL

参数编辑

  • haystack
  • 输入字符串。
  • needle
  • 如果 needle 不是一个字符串,那么它将被转化为整型并且作为字符的序号来使用。
  • before_needle
  • 若为  TRUEstrstr() 将返回 needle 在 haystack 中的位置之前的部分。
返回: 返回字符串的一部分或者  FALSE(如果未发现 needle)。
例子:
1
2
3
4
5
6
7
<?php
$email = 'name@example.com' ;
$domain = strchr ( $email , '@' );
echo $domain ; //打印@example.com
$user = strchr ( $email , '@' ,true); //从PHP5.3.0起
echo $user ; //打印name
?>

函数公式编辑

实现:
1
2
3
4
5
6
7
8
char * strchr ( char *s,charc)
{
while (*s!= '\0' &&*s!=c)
{
++s;
}
return *s==c?s:NULL;
}

范例

举例1:(在 Visual C++ 6.0中运行通过)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <string.h>
#include <stdio.h>
int  main( void )
{
     char  string[17];
     char  *ptr,c= 'r' ;
     strcpy (string, "Thisisastring" );
     ptr= strchr (string,c);
     if (ptr)
         printf ( "Thecharacter%cisatposition:%s\n" ,c,ptr);
     else
         printf ( "Thecharacterwasnotfound\n" );
     return0;
}
运行结果:
The character r is at position: ring
请按任意键继续. . .
举例2:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// strchr.c
#include <stdio.h>
#include <string.h>
int  main()
{
     char  temp[32];
     memset (temp,0, sizeof (temp));
     strcpy (temp, "Golden Global View" );
     char  *s = temp;
     char  *p,c= 'v' ;
     p= strchr (s,c);
     if (p)
         printf ( "%s" ,p);
     else
         printf ( "Not Found!" );  return  0;
}
运行结果:Not Found!Press any key to continue
举例3:
1
2
3
4
5
6
7
8
9
10
11
#include <stdio.h>
#include <string.h>
void  main()
{
     char  answer[100],*p;
     printf ( "Type something:\n" );
     fgets (answer, sizeof  answer,stdin);
     if ((p =  strchr (answer, '\n' )) != NULL)
         *p =  '\0' ; //手动将\n位置处的值变为0
     printf ( "You typed \"%s\"\n" ,answer);
}
fgets不会像gets那样自动地去掉结尾的\n,所以程序中手动将\n位置处的值变为\0,代表输入的结束。

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值