网站首页 语言 会计 电脑 医学 资格证 职场 文艺体育 范文
当前位置:书香门第 > 计算机 > C语言

C语言入门知识:strchr函数

栏目: C语言 / 发布于: / 人气:2.75W

导语: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=&#';

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

echo$domain;//打印@

$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!=''&&*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

// strchr.c

#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 = '';//手动将位置处的值变为0

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

}

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