strchr Function

Locates the first occurrence of a specified character in a string.

Include

<string.h>

Prototype

char *strchr(const char *s, int c);

Arguments

s
pointer to the string
c
character to search for

Return Value

Returns a pointer to the location of the match if successful; otherwise, returns a null pointer.

Remarks

This function searches the string s to find the first occurrence of the character, c.

Example

See the notes at the beginning of this chapter or section for information on using printf() or scanf() (and other functions reading and writing the stdin or stdout streams) in the example code.

#include <string.h>
#include <stdio.h>

int main(void)
{
  char buf1[50] = "What time is it?";
  char ch1 = 'm', ch2 = 'y';
  char *ptr;
  int res;

  printf("buf1 : %s\n\n", buf1);

  ptr = strchr(buf1, ch1);
if (ptr != NULL)
  {
    res = ptr - buf1 + 1;
    printf("%c found at position %d\n", ch1, res);
  }
  else
    printf("%c not found\n", ch1);
  printf("\n");

  ptr = strchr(buf1, ch2);
if (ptr != NULL)
  {
    res = ptr - buf1 + 1;
    printf("%c found at position %d\n", ch2, res);
  }
  else
    printf("%c not found\n", ch2);
}

Example Output

buf1 : What time is it?

m found at position 8

y not found