strstr in C
strstr is a function in C that is used to find the first occurrence of a substring in a string. It is declared in the <string.h> header.
Syntax:
char *strstr(const char *str1, const char *str2);
- str1 → The main string in which you want to search.
- str2→ The substring you are searching for.
- A pointer to the first occurrence of str2 in str1.
- NULL if str2 is not found.
Example:
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello, welcome to C programming!";
char substr[] = "welcome";
// Using strstr to find substring
char *result = strstr(str, substr);
if (result != NULL) {
printf("Substring found at position: %ld\n", result - str);
} else {
printf("Substring not found.\n");
}
return 0;
}
Output:
Substring found at position: 7
No comments:
Post a Comment