String search
- C course
- Intermediate
- Lesson 20/116
- 5 min
Learn advanced search with strstr and strchr.
Substring search with strstr
strstr(haystack, needle) searches for the needle substring inside haystack. On success it returns the address of the first match; on failure it returns NULL.
Example: char *r = strstr("Merhaba dünya", "dün");. Here r holds the start address of the "dünya" part. printf("%s\n", r); prints "dünya". strstr is case-sensitive; "Dün" and "dün" differ. It's good practice to check for NULL before using the result.
Character search with strchr
strchr(s, c) searches for the character c in the string s. On success it returns the address of the first match; on failure it returns NULL.
Example: char *p = strchr("Merhaba", 'a');. Here p holds the address of the first 'a'. While strstr searches substrings, strchr searches a single character. Both return NULL on failure; so the result should be checked before use. Character search is common in parsing and format handling.
Practice Find and print a substring
Search for the substring with char *r = strstr("Merhaba dünya", "dün");. Print the matched part with printf("%s\n", r);. Include <string.h>.
Starter code
#include <stdio.h>
#include <string.h>
// Search for "dün" with strstr
// Print the matched part with printf
int main(void) {
return 0;
}Sample solution
#include <stdio.h>
#include <string.h>
int main(void) {
char *r = strstr("Merhaba dünya", "dün");
printf("%s\n", r);
return 0;
}Expected output
dünya
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the strstr call
char *r = ____("Merhaba dünya", "dün");
char *r = strstr("Merhaba dünya", "dün");
Explanation: strstr searches for a substring.
2 Match the search functions
| Term | Meaning |
|---|---|
strstr |
Searches substring |
strchr |
Searches character |
NULL return |
Not found |
address return |
Found |
3 What does strstr return if not found?
- Empty string
- NULL Correct answer
- -1
- Index 0
Explanation: strstr returns NULL on failure; so the result should be checked before use.