C Library Functions -strchr()
C Standard Library - <string.h>
Description
strchr() is used to search for a character in a string and return the position of the first occurrence of that character in the string.
strchr(), whose prototype is defined in the header file <string.h>,char *strchr(const char *str, int c)In the parameterstrSearch for the first occurrence of a character in the string pointed tocthe position of (an unsigned character).
The pointer returned by the strchr() function points to a 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)
Parameter
- 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 <string.h>
int main ()
{
const char str[] = "https://www.example.com";
const char ch = 'o';
char *ptr;
ptr = strchr(str, ch);
if (ptr != NULL) {
printf("The position where character 'o' appears is %ld.\n", ptr - str + 1);
printf("The string after |%c| is - |%s|\n\n", ch, ptr);
} else {
printf("Character 'o' not found.\n");
}
return(0);
}
In the above example, the strchr() function searches for the first occurrence of the character 'o' in the string "https://www.example.com". Since this character appears at position 15, the pointer ptr points to the 16th character in the string.
Let us compile and run the above program, this will produce the following result:
字符 'o' 出现的位置为 16。 |o| 之后的字符串是 - |oob.com|other extensions