Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C

strchr — first occurrence of a character

strchr finds the first occurrence of a character in a C string, returning a pointer or NULL.

Version: C23; repository compiler flag, production runtime not attested

Syntax

#include <string.h>
QChar *strchr(QChar *s, int c);

strchr from <string.h> finds the first character equal to c converted to char. It returns its pointer or NULL. Searching for \0 finds the terminator.

In C23, QChar here denotes char or const char, not a type to declare. The generic call preserves const: const char * yields const char *.

s must point to a valid null-terminated string; NULL is invalid. Check the result before dereferencing. The example prints a zero-based index and an unsuccessful search result.

Examples

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

int main(void)
{
    const char text[] = "banana";
    const char *p = strchr(text, 'a');

    if (p != NULL) {
        printf("%td\n", p - text);
    }
    puts(strchr(text, 'z') == NULL ? "missing" : "found");
    return 0;
}

Result

1
missing

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources