C++ wcsspn()

The wcsspn() function returns the length of maximum initial segment of the wide string that consists of characters present in another wide string.

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

wcsspn() prototype

size_t wcsspn( const wchar_t* dest, const wchar_t* src );

The wcsspn() function in C++ takes two null terminated wide strings: dest and src as its argument and gives the length of maximum initial segment of the wide string pointed to by dest that consists of characters that are present in the wide string pointed to by src.


wcsspn() Parameters

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

wcsspn() Return value

The wcsspn() function returns the length of the maximum initial segment of dest that contains only the wide characters from wide string pointed to by src.


Example: How wcsspn() function works?

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

int main()
{
	setlocale(LC_ALL, "en_US.utf8");
	
	wchar_t src[] = L"0123456789";
	wchar_t dest[] = L"\u0036\u0030\u0038\u0031\u004d\u00c6\u0137\u0027\u0426";
	int length = wcsspn(dest, src);
	
	if (length>0)
		wcout << dest << L" contains " << length << L" initial numbers";
	else
		wcout << dest << L" doesn't start with numbers";
	
	return 0;
}

When you run the program, the output will be:

6081MÆķ'Ц contains 4 initial numbers