YouTip LogoYouTip

C Function Strstr

# C Library Function - strstr() [![Image 3: C Standard Library - ](#) C Standard Library - ](#) ## Description The C library function **char *strstr(const char *haystack, const char *needle)** finds the first occurrence of the string **needle** in the string **haystack**, not including the terminating null character (). strstr() is a string handling function in the C standard library used to find the first occurrence of a substring within a string. ## Declaration Below is the declaration for the strstr() function. char *strstr(const char *haystack, const char *needle); The strstr() function is used to find the first occurrence of the substring needle in the string haystack. If found, it returns a pointer to that location; if not found, it returns NULL. ## Parameters * **haystack** -- The main string to be searched. * **needle** -- The substring to be searched for. ## Return Value Returns a pointer to the first occurrence of needle in haystack. If needle is not found in haystack, NULL is returned. ## Example The following example demonstrates the usage of the strstr() function. ## Example 1 #include#includeint main(){const char haystack = "TUTORIAL"; const char needle = "NOOB"; char *ret; ret = strstr(haystack, needle); printf("Substring is: %sn", ret); return(0); } Let us compile and run the above program, this will produce the following result: Substring is: NOOB ## Example 2 #include #include int main(){ const char*haystack ="Hello, world! This is a test string."; const char*needle ="world"; // Find needle in haystack char*result =strstr(haystack, needle); if(result != NULL){ printf("Substring found: %sn", result); }else{ printf("Substring not found.n"); } return 0; } **Code Explanation:** * The `strstr()` function starts searching for `needle` from the beginning of `haystack` until a match is found or the end of `haystack` is reached. * If `needle` is an empty string (`""`), `strstr()` returns the starting address of `haystack`. * `strstr()` is case-sensitive. If a case-insensitive search is needed, you can use `strcasestr()` (a non-standard function that may require specific library support). Output: Substring found: world! This is a test string. [![Image 4: C Standard Library - ](#) C Standard Library - ](#)
← Md TitleFunc String Mb_Substr β†’