Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

C Library Function - strstr()

C Library Function - strstr()

C Standard Library - <string.h> C Standard Library -

Description

C Library Function **char *strstr(const char *haystack, const char *needle) ** searches the string haystack for the first occurrence of the string needle , excluding the terminating \0.

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 of the strstr() function.



char *strstr(const char *haystack, const char *needle);

The strstr() function finds the first occurrence of the substring needle in the string haystack. If found, it returns a pointer to that position; if not found, it returns NULL.

Parameters

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 use of the strstr() function.

Example 1

#include

<

stdio.h

#include

<

string.h

int

main

(

)

{

const

char

haystack

[

20

]

=

"

RUNOOB

"

;

const

char

needle

[

10

]

=

"

NOOB

"

;

char

ret

;

ret

=

strstr

(

haystack

,

needle

)

;

printf

(

"

The substring is: %s

\

n

"

,

ret

)

;

return

(

0

)

;

}

Let's compile and run the above program, which will produce the following result:



子字符串是: 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: %s\n"

,

result

)

;

   

}

else

{

       

printf

(

"Substring not found.\n"

)

;

   

}

   

return

0

;

}

Code explanation:

Output result:



Substring found: world! This is a test string.

C Standard Library - <string.h> C Standard Library -