C++ wcsstr()

The wcsstr() function in C++ finds the first occurrence of a wide substring in a wide string.

The wcsstr() function is defined in <cwchar> header file.

wcsstr() prototype

const wchar_t* wcsstr( const wchar_t* dest, const wchar_t* src );
wchar_t* wcsstr( wchar_t* dest, const wchar_t* src )

The wcsstr() function takes two arguments: dest and src. It searches for the first occurrence of src in the wide string pointed to by dest. The terminating null wide characters are ignored.


wcsstr() Parameters

  • dest: Pointer to the null terminated wide string to be searched for.
  • src: Pointer to the null terminated wide string to search for.

wcsstr() Return value

  • If the substring is found, the wcsstr() function returns the pointer to the first wide character of the substring in dest.
  • If the substring is not found, a null pointer is returned.
  • If src points to an empty string, dest is returned.

Example: How wcsstr() function works?

#include <cwchar>
#include <clocale>
#include <iostream>
using namespace std;

int main()
{
	setlocale(LC_ALL, "en_US.utf8");
	
	wchar_t src[] = L"ĸņoŵ";
	wchar_t dest[] = L"You must ĸņoŵ these facts";
	wchar_t *p = wcsstr(dest, src);
	
	if (p)
		wcout << L"\"" << src << L"\" is present in \"" << dest << L"\" at position " << (p-dest);
	else
		wcout << L"\"" << src << L"\" is not present in \"" << dest << L"\"";
	
	return 0;
}

When you run the program, the output will be:

"ĸņoŵ" is present in "You must ĸņoŵ these facts" at position 9
Did you find this article helpful?