This function searches for the first occurrence of a substring within a string.
Syntax:
char *strstr(const char *str1, const char *str2);
Parameters:
- str1: A pointer to the main string to search within.
- str2: A pointer to the substring to search for.
Return Value:
- A pointer to the first occurrence of the substring str2 in str1.
- if the substring is not found then return NULL.
Example:
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "My World!";
char substr[] = "World";
char *result = strstr(str, substr);
if (result != NULL) {
printf("Substring found: %s\n", result); // Output: World!
} else {
printf("Substring not found.\n");
}
return 0;
}
Output:
Substring found: World!
C strstr() method – Interview Questions
Q 1: What does strstr() do?
Ans: It finds the first occurrence of a substring.
Q 2: What is the return type of strstr()?
Ans: Pointer to the substring or NULL.
Q 3: Is strstr() case-sensitive?
Ans: Yes.
Q 4: Which header file contains strstr()?
Ans: <string.h>.
Q 5: What happens if substring is empty?
Ans: It returns the original string pointer.
C strstr() method – Objective Questions (MCQs)
Q1. What does the strstr() function in C do?
Q2. What is the return type of strstr() function?
Q3. What will strstr("Hello World", "World") return?
Q4. What will strstr("Programming", "xyz") return?
Q5. Which header file must be included to use strstr() function?