The wcsstr
function looks for the first occurrence of a wide string in another wide string. It is defined in the <wchar.h>
header file.
wchar_t* wcsstr(wchar_t* haystack, wchar_t* needle);
In the above snippet of code, both haystack
and needle
are pointers to two separate wide strings. When we call the function, the first occurrence of needle
is searched in haystack
.
If needle
is found in haystack
, a pointer to its first occurrence is returned.
Else, NULL
is returned.
If needle
is empty, a pointer to the beginning of haystack
is returned.
As shown in the figure above, the pointer returned from the function points to the beginning of first occurrence of needle
in haystack
. The code for the above drawn figure is written below:
#include<stdio.h>#include<wchar.h>void main() {// declaring and initializing strings of wide characterswchar_t haystack[] = L"HELLOWORLD!";wchar_t needle[] = L"LLO";// calling the function and storing the returned value in a pointerwchar_t* returnedPtr = wcsstr(haystack, needle);// checking if the substring was foundif(returnedPtr == NULL) {printf("SUBSTRING NOT FOUND \n");}else {// printing the returned string/pointerwprintf(L"%ls", returnedPtr);}}
In the above snippet of code, we are searching for the substring LLO in the string HELLOWORLD. The returnedPtr
pointer points to the first L in the string haystack
. Due to this, when we call the wprintf
function on the returned pointer, it prints from the first L till the end of haystack
.
Note that we used
L
prefix while declaring and initializing wide strings andwprintf
function to print a wide string.
#include<stdio.h>#include<wchar.h>void main() {// declaring and initializing strings of wide characterswchar_t haystack[] = L"HELLOWORLD!";wchar_t needle[] = L"";// calling the function and storing the returned value in a pointerwchar_t* returnedPtr = wcsstr(haystack, needle);// checking if the substring was foundif(returnedPtr == NULL) {printf("SUBSTRING NOT FOUND \n");}else {// printing the returned string/pointerwprintf(L"%ls", returnedPtr);}}
As shown in the above code snippet, the wcsstr
function returns a pointer to the beginning of haystack
if needle
is empty.