strchr() in C: Find a Character

strchr() searches a string for the first occurrence of a character. It returns a pointer to the matching character, or NULL when no match exists.

Syntax Top ↑

char *match = strchr(string, character);

Find the First Matching Character Top ↑

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

int main(void) {
    char text[] = "Welcome to plus2net";
    char *match = strchr(text, 'm');

    if (match != NULL) {
        size_t position = (size_t)(match - text);
        printf("Character: %c\n", *match);
        printf("Zero-based position: %zu\n", position);
        printf("From the match: %s\n", match);
    }

    return 0;
}

Always Check for NULL Before Dereferencing Top ↑

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

int main(void) {
    char text[] = "C programming is fun!";
    char target = 'z';
    char *match = strchr(text, target);

    if (match != NULL) {
        printf("Found %c.\n", *match);
    } else {
        printf("Character not found.\n");
    }

    return 0;
}

Dereferencing a NULL pointer with *match is invalid, so the pointer must be checked first.

Search User Input Top ↑

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

int main(void) {
    char text[100];
    char target;

    printf("Enter a string: ");
    if (fgets(text, sizeof(text), stdin) == NULL) {
        return 1;
    }
    text[strcspn(text, "\n")] = '\0';

    printf("Enter a character: ");
    if (scanf(" %c", &target) != 1) {
        return 1;
    }

    char *match = strchr(text, target);
    if (match != NULL) {
        printf("Found at zero-based position %zu.\n", (size_t)(match - text));
    } else {
        printf("Character not found.\n");
    }

    return 0;
}




plus2net.com






✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer