What is wcsspn in C?

wcsspn in C returns the length of the maximum initial portion of a wide string whose characters are present in another wide string. wcsspn is defined in the wchar.h header and its function declaration in the standard C library is as follows:

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

A wide string uses characters from the Unicode character set, where typically each character is of 2 bytes

Parameters

dest: the wide string that is to be analyzed

src: the wide string that contains the characters to search for

Return value

Maximum initial portion of dest whose characters are present in src.

In C++, wcsspn is defined in the cwchar header.

Example

#include <wchar.h>
int main ()
{
int length1, length2, length3;
wchar_t src1[] = L"2021 is going to be my year";
wchar_t src2[] = L"20-20 is the best format for cricket";
wchar_t src3[] = L"Edpresso-a shot of dev knowledge";
wchar_t dest[] = L"2021Edpresso";
length1 = wcsspn(dest,src1);
length2 = wcsspn(dest,src2);
length3 = wcsspn(dest,src3);
wprintf(L"Example 1. Length of initial matching characters: %d\n",length1);
wprintf(L"Example 2. Length of initial matching characters: %d\n",length2);
wprintf(L"Example 3. Length of initial matching characters: %d\n",length3);
return 0;
}

Explanation

First, we import the wchar.h header file. In lines 7-11, we initialize the destination and source strings, where the L identifier before the string indicates that the characters to follow are from the Unicode character set.

  • In Example 1, the length is 4 because the initial matching wide string in dest is 2021.
  • In Example 2, the length is 3 because the initial matching wide string in dest is 202.
  • In Example 3, the length is 0 because there is no initial matching wide string in dest. Although Edpresso is part of both wide strings, dest starts with 2 and is not part of the initial portion of dest.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved