C++ wcscspn()

The wcscspn() function in C++ searches and returns the number of wide characters before the first occurrence of any wide character in the given wide string.

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

wcscspn() prototype

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

If either src or dest does not point to a null terminated wide string, the behaviour of wcscspn() function is undefined.


wcscspn() 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.

wcscspn() Return value

The wcscspn() function returns number of wide characters in dest before the first occurrence of any wide characters present in src.


Example: How wcscspn() 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"\u222b\u0028\u0078\u002b\u0032\u0029\u0064\u0078";
	int result = wcscspn(dest, src);
	
	if (result < wcslen(dest))
		wcout << L"First occurrence of number in " << dest << " is at position " << result;
	else
		wcout << dest << L" does not contain numbers";
	
	return 0;
}

When you run the program, the output will be:

First occurrence of number in ∫(x+2)dx is at position 4