The function strchr() searches the occurrence of a specified character in the given string and returns the pointer to it.
C strchr() Function
char *strchr(const char *str, int ch)
str – The string in which the character is searched.
ch – The character that is searched in the string str.
Return Value of strchr()
It returns the pointer to the first occurrence of the character in the given string, which means that if we display the string value of the pointer then it should display the part of the input string starting from the first occurrence of the specified character.
Example: strchr() function in C
In this example, we have a string and we are searching a character ‘u’ in the string using strchr() function. When we displayed the string value of the returned pointer of the function, it displayed the string starting from the character ‘u’, this is because the pointer returned by the function points to the character ‘u’ in the string.
#include <stdio.h> #include <string.h> int main () { const char str[] = "This is just a String"; const char ch = 'u'; char *p; p = strchr(str, ch); printf("String starting from %c is: %s", ch, p); return 0; }
Output:
String starting from u is: ust a String
Roman Horváth says
It is not written anywhere what happens when a character is not found. Now I know – the function returns null. This is important information…