C - strstr() function
C strstr() function - Find a substring
Syntax:
char *strstr(const char *string1, const char *string2)
The strstr() function is used to find the first occurrence of string2 in string1. The function ignores the null character (\0) that ends string2 in the matching process.
Parameters:
Name | Description | Required /Optional |
---|---|---|
string1 | Null-terminated string to search. | Required |
string2 | Null-terminated string to search for. | Required |
Return value from strstr()
- Returns a pointer to the first occurrence of string2 in string1, or NULL if string2 doesn't appear in string1.
- If string2 points to a string of zero length, the function returns string1.
Example: strstr() function
#include <string.h>
#include <stdio.h>
int main(void)
{
char string1[] = "C Programming";
char string2[] = "ming";
char *result;
printf("String1 = %s",string1);
printf("\nString2 = %s",string2);
result = strstr(string1,string2);
printf("\nFind the first occurrence of string2 in string1 = %s\n", result);
char string3[] = "mng";
result = strstr(string1,string3);
printf("\n\nString1 = %s",string1);
printf("\nString3 = %s",string3);
printf("\n\Find the first occurrence of string3 in string1 = %s\n", result);
}
Output:
String1 = C Programming String2 = ming Find the first occurrence of string2 in string1 = ming String1 = C Programming String3 = mng Find the first occurrence of string3 in string1 = (null)
C Programming Code Editor:
Previous C Programming: C strspn()
Next C Programming: C strtok()
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/c-programming/string/c-strstr.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics