C语言入门知识:strchr函数

时间:2025-11-02 14:28:14 C语言

C语言入门知识:strchr函数

  导语:strchr函数原型:extern char *strchr(const char *s,char c);查找字符串s中首次出现字符c的位置。下面是C语言strchr函数知识,欢迎阅读:

C语言入门知识:strchr函数

  C语言

  char *strchr(const char* _Str,int _Val)

  char *strchr(char* _Str,int _Ch)

  头文件:#include

  功能:查找字符串s中首次出现字符c的位置

  说明:返回首次出现c的位置的指针,返回的地址是被查找字符串指针开始的第一个与Val相同字符的指针,如果s中不存在c则返回NULL。

  返回值:成功则返回要查找字符第一次出现的位置,失败返回NULL

  参数编辑

  haystack

  输入字符串。

  needle

  如果 needle 不是一个字符串,那么它将被转化为整型并且作为字符的序号来使用。

  before_needle

  若为 TRUE,strstr() 将返回 needle 在 haystack 中的位置之前的部分。

  返回: 返回字符串的一部分或者 FALSE(如果未发现 needle)。

  例子:

  1

  2

  3

  4

  5

  6

  7

  

  $email='name@example.com';

  $domain=strchr($email,'@');

  echo$domain;/pic/p>

  $user=strchr($email,'@',true);/pic/p>

  echo$user;/pic/p>

  ?>

  函数公式编辑

  实现:

  1

  2

  3

  4

  5

  6

  7

  8

  char*strchr(char*s,charc)

  {

  while(*s!=''&&*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

  #include

  int main(void)

  {

  char string[17];

  char *ptr,c='r';

  strcpy(string,"Thisisastring");

  ptr=strchr(string,c);

  if(ptr)

  printf("Thecharacter%cisatposition:%s ",c,ptr);

  else

  printf("Thecharacterwasnotfound ");

  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

  /pic/p>

  #include

  #include

  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

  #include

  void main()

  {

  char answer[100],*p;

  printf("Type something: ");

  fgets(answer,sizeof answer,stdin);

  if((p = strchr(answer,' ')) != NULL)

  *p = '';/pic/p>

  printf("You typed "%s" ",answer);

  }

  fgets不会像gets那样自动地去掉结尾的 ,所以程序中手动将 位置处的值变为,代表输入的结束。


【C语言入门知识:strchr函数】相关文章:

C语言入门知识:strstr函数10-09

C语言入门知识:realloc函数03-18

C语言函数入门学习12-18

C语言入门知识12-03

C语言入门知识:常量03-07

C语言入门必备知识09-29

C语言中gets()函数知识01-23

c语言入门基础知识06-25

C语言入门知识:转义字符07-24