C strstr() Function
strstr() searches for a substring in a string. It returns a pointer to the first place where it is found, or NULL if it is not found.
Syntax
char *strstr(const char *text, const char *sub);
Example
#include <stdio.h>
#include <string.h>
int main(void) {
char text[] = "I am learning C programming";
char *p = strstr(text, "learning");
if (p != NULL) {
printf("Found: %s\n", p);
printf("Position: %ld\n", p - text);
} else {
printf("Not found\n");
}
return 0;
}
Output:
Output of the above program is
Found: learning C programming
Position: 5
p - text is the number of characters before the match, so it gives the index (starting from 0).
When the word is missing
#include <stdio.h>
#include <string.h>
int main(void) {
char *p = strstr("Hello World", "Java");
if (p == NULL) {
printf("Not found\n");
}
return 0;
}
Output:
Output of the above program is
Not found
Note:
Always check for NULL before using the pointer. The search is case sensitive, so “learning” and “Learning” are different.
Next: Reverse a String in C.
Congratulations! Chapter Finished. Learn more about the similar topics:
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |