C Library Function - strchr()
Description
strchr() is used to find a character in a string and returns the position of its first occurrence in the string.
strchr() whose prototype is defined in the header file
The pointer returned by the strchr() function points to the character in the string; if you want to use this pointer as a string, you should pass it to other string-handling functions, such as printf() or strncpy().
Declaration
Below is the declaration of the strchr() function.
char *strchr(const char *str, int c)
Parameters
- str -- the string to search.
- c -- the character to find.
Return Value
If the character c is found in the string str, the function returns a pointer to that character; if the character is not found, it returns NULL.
Example
The following example demonstrates the use of the strchr() function.
Example
#include
#include
int
main
(
)
{
const
char
str
[
]
=
"https://www.runoob.com"
;
const
char
ch
=
'o'
;
char
ptr
;
ptr
=
strchr
(
str
,
ch
)
;
if
(
ptr
!=
NULL
)
{
printf
(
"The character 'o' appears at position %ld.\n"
,
ptr
str
1
)
;
printf
(
"The string after |%c| is - |%s|\n"
,
ch
,
ptr
)
;
}
else
{
printf
(
"Character 'o' not found.\n"
)
;
}
return
(
0
)
;
}
In the above example, the strchr() function finds the first occurrence of the character 'o' in the string "https://www.runoob.com". Since the character appears at position 15, the pointer ptr points to the 16th character in the string.
Let's compile and run the above program, which will produce the following result:
字符 'o' 出现的位置为 16。
|o| 之后的字符串是 - |oob.com|
C Standard Library -