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.
char *match = strchr(string, character);
#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;
}
#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.
#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;
}
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.