C - strchr() function
C strchr() function - string scanning operation
The strchr() function is used to find the first occurrence of a character in a given string or it returns NULL if the character is not found. The null terminating character is included in the search.
Syntax:
char *strchr(const char *str, int c)
Parameters:
Name | Description | Required /Optional |
---|---|---|
str | Null-terminated source string. | Required |
c | Character to be located. | Required |
Return value from strchr()
Upon completion, strchr() shall return a pointer to the byte, or a null pointer if the byte was not found.
Example: strchr() function
This example finds the first occurrence of the character "C", "g", "a" and "." in "C Programming.".
#include <stdio.h>
#include <string.h>
#define SIZE 40
int main(void)
{
char str1[SIZE] = "C Programming.";
int ch = 'C';
char* ptr = strchr(str1, ch);
printf( "The first occurrence of %c in '%s' is '%d'\n",
ch, str1, ptr - str1 + 1 );
ch = 'a';
ptr = strchr(str1, ch);
printf( "The first occurrence of %c in '%s' is '%d'\n",
ch, str1, ptr - str1 + 1 );
ch = 'g';
ptr = strchr(str1, ch);
printf( "The first occurrence of %c in '%s' is '%d'\n",
ch, str1, ptr - str1 + 1 );
ch = '.';
ptr = strchr(str1, ch);
printf( "The first occurrence of %c in '%s' is '%d'\n",
ch, str1, ptr - str1 + 1 );
}
Output:
The first occurrence of C in 'C Programming.' is '1' The first occurrence of a in 'C Programming.' is '8' The first occurrence of g in 'C Programming.' is '6' The first occurrence of . in 'C Programming.' is '14'
C Programming Code Editor:
Previous C Programming: C strncat()
Next C Programming:C strcmp()
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics