Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

C Library Function – strchr()

C Library Function - strchr()

C Standard Library - <string.h> C Standard Library -

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 , **char strchr(const char str, int c) Searches the first str searches for the first occurrence of the character in the string pointed to by cand returns its position.

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

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 - <string.h> C Standard Library -