How to Find Substring in C: Simple Guide with Examples
In C, you can find a substring inside a string using the
strstr function from string.h. It returns a pointer to the first occurrence of the substring or NULL if not found.Syntax
The strstr function is declared in string.h and used like this:
char *strstr(const char *haystack, const char *needle);
Here, haystack is the main string to search in, and needle is the substring you want to find.
The function returns a pointer to the first occurrence of needle in haystack, or NULL if needle is not found.
c
char *strstr(const char *haystack, const char *needle);
Example
This example shows how to use strstr to find a substring and print its position or a message if not found.
c
#include <stdio.h> #include <string.h> int main() { const char *text = "Hello, welcome to C programming."; const char *sub = "welcome"; char *pos = strstr(text, sub); if (pos != NULL) { printf("Substring found at position: %ld\n", pos - text); } else { printf("Substring not found.\n"); } return 0; }
Output
Substring found at position: 7
Common Pitfalls
Common mistakes when using strstr include:
- Not checking if the return value is
NULLbefore using it. - Confusing the returned pointer with an index; you must subtract the original string pointer to get the position.
- Passing
NULLor uninitialized strings tostrstr, which causes undefined behavior.
c
#include <stdio.h> #include <string.h> int main() { const char *text = "example text"; const char *sub = "text"; // Wrong: Using strstr return value without NULL check // printf("Position: %ld\n", strstr(text, sub) - text); // Unsafe if substring not found // Right: Check for NULL before using char *pos = strstr(text, sub); if (pos) { printf("Position: %ld\n", pos - text); } else { printf("Substring not found.\n"); } return 0; }
Output
Position: 8
Quick Reference
| Function | Description |
|---|---|
| strstr(haystack, needle) | Returns pointer to first occurrence of needle in haystack or NULL if not found |
| Return value | Pointer to substring start or NULL |
| Include header | |
| Check for NULL | Always check before using the returned pointer |
| Position calculation | Use pointer subtraction: pos - haystack |
Key Takeaways
Use
strstr from string.h to find substrings in C strings.Always check if
strstr returns NULL before using the result.Calculate substring position by subtracting the original string pointer from the returned pointer.
Passing uninitialized or NULL strings to
strstr causes errors.Remember
strstr finds the first occurrence only.