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的位置
返回值:成功则返回要查找字符第一次出现的位置,失败返回NULL
参数编辑
-
haystack
-
输入字符串。
-
needle
-
如果 needle 不是一个字符串,那么它将被转化为整型并且作为字符的序号来使用。
-
before_needle
-
若为 TRUE, strstr() 将返回 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,代表输入的结束。