Strchr
Jump to navigation
Jump to search
Syntax
char * strchr ( const char *string, int searchedChar );
Description
Locate first occurrence of character in string
Returns a pointer to the first occurrence of character in the C string str.
The terminating null-character is considered part of the C string. Therefore, it can also be located in order to retrieve a pointer to the end of a string.
Parameters
- str
- C string.
- character
- Character to be located. It is passed as its int promotion, but it is internally converted back to char for the comparison.
Return Value
A pointer to the first occurrence of character in str.
If the character is not found, the function returns a null pointer.
Example
Source | Output |
---|---|
#include <stdio.h>
#include <string.h>
void searchChar(char *str, int chr);
int main(int argc, char *argv[])
{
char string[] = "Hello world!";
searchChar(string, '?');
searchChar(string, 'l');
searchChar(string, '!');
searchChar(string, 'o');
}
void searchChar(char *str, int chr)
{
if (strchr(str, chr)) {
printf("'%c' found\n", chr);
} else {
printf("'%c' not found\n", chr);
}
}
|
'?' not found 'l' found '!' found 'o' found |