C Function Strchr
# C Library Function - strchr()
[ C Standard Library - ](#)
## Description
strchr() is used to find a character in a string and returns the position of the first occurrence of that character in the string.
The prototype of strchr() is defined in the header file . **char *strchr(const char *str, int c)** searches for the first occurrence of character **c** (an unsigned character) in the string pointed to by parameter **str**.
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 be searched.
* **c** -- The character to be searched for.
## 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 usage of the strchr() function.
## Example
#include
#include
int main ()
{
const char str[]="";
const char ch ='o';
char*ptr;
ptr =strchr(str, ch);
if(ptr != NULL){
printf("The character 'o' is found at position %ld.n", ptr - str +1);
printf("The string after |%c| is - |%s|n", ch, ptr);
}else{
printf("The character 'o' was not found.n");
}
return(0);
}
In the above example, the strchr() function searches for the first occurrence of the character 'o' in the string "". Since this 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:
The character 'o' is found at position 16.
The string after |o| is - |oob.com|
[ C Standard Library - ](#)
YouTip