locate character in string

You're viewing an older version of this page (#3497). View the current version.

View versions (3)

INTERFACE

#include <string.h> char * strchr ( const char *s, int c ) char * strrchr ( const char *s, int c )

DESCRIPTION

The strchr function locates the first occurrence of c (converted to a char) in the string pointed to by s. The terminating null character is considered part of the string; therefore if c is '\\0', the functions locate the terminating '\\0'.

The strrchr function is identical to strchr except it locates the last occurrence of c.

Example 1

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

int main()
{
  // define some string
  char s[10] = "abcdefgh";

  // look for the character 'e' in the string s
  char *pos = strchr(s, 'e');

  // display search result
  if (pos)
    printf("Character 'e' found at position %d.\n", pos - s);
  else
    printf("Character 'e' not found.\n");

  return 0;
}

Output:

Character 'e' found at position 4.

RETURN VALUES

The functions strchr and strrchr return a pointer to the located character, or NULL if the character does not appear in the string.

SEE ALSO

memchr, strcspn, strpbrk, strspn, strstr, strtok

STANDARDS

The functions strchr and strrchr conform to ISO/IEC 9899:1990 ("ISO C90").