strstr() searches a string for the first occurrence of another string. It returns a pointer to the start of the matching substring, or NULL when the substring is not found.
char *match = strstr(main_string, search_string);
#include <stdio.h>
#include <string.h>
int main(void) {
char text[] = "Welcome to C section of plus2net";
char search[] = "to C";
char *match = strstr(text, search);
if (match != NULL) {
printf("Zero-based position: %zu\n", (size_t)(match - text));
printf("From the match: %s\n", match);
} else {
printf("Substring not found.\n");
}
return 0;
}
#include <stdio.h>
#include <string.h>
int main(void) {
char text[] = "C programming is fun";
char word[] = "fun";
if (strstr(text, word) != NULL) {
printf("The word %s was found.\n", word);
} else {
printf("The word was not found.\n");
}
return 0;
}
#include <stdio.h>
#include <string.h>
int main(void) {
char text[100];
char search[50];
printf("Enter a string: ");
if (fgets(text, sizeof(text), stdin) == NULL) {
return 1;
}
text[strcspn(text, "\n")] = '\0';
printf("Enter a substring: ");
if (fgets(search, sizeof(search), stdin) == NULL) {
return 1;
}
search[strcspn(search, "\n")] = '\0';
char *match = strstr(text, search);
if (match != NULL) {
printf("Found at zero-based position %zu.\n", (size_t)(match - text));
} else {
printf("Substring not found.\n");
}
return 0;
}
The second argument to strstr() must be a string. To search for one character, use strchr().
The original page included a search-and-replacement example. This safer version builds the result in a separate destination buffer instead of overwriting an unknown amount of storage at the match position.
#include <stdio.h>
#include <string.h>
int main(void) {
const char text[] = "Welcome to C section of plus2net";
const char search[] = "to C section";
const char replacement[] = "to PHP section";
char result[100];
const char *match = strstr(text, search);
if (match == NULL) {
printf("No match found.\n");
return 0;
}
size_t prefix = (size_t)(match - text);
int written = snprintf(result, sizeof result,
"%.*s%s%s",
(int)prefix, text,
replacement,
match + strlen(search));
if (written < 0 || (size_t)written >= sizeof result) {
printf("Replacement did not fit.\n");
return 1;
}
printf("%s\n", result);
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.