What is wcslen in C?
The wcslen function in C returns the number of characters in a wide string, excluding the null terminating character.
The process is illustrated below:
Note: A
wide stringis comprised of characters from the Unicode character set.
To use the wcslen function, you will need to include the <wchar.h> library in the program, as shown below:
#include <wchar.h>
The prototype of the wcslen function is shown below:
size_t wcslen(const wchar_t *str);
Parameters
The wcslen function takes a single parameter, i.e., a pointer to a null-terminated wide string.
Return Value
The wcslen function returns the length of the given wide string, excluding the null-terminating character.
Example
The code below shows how the wcslen function works in C:
#include <stdio.h>#include <wchar.h>int main() {// initializing wide stringwchar_t str1[] = L"Hello World";wchar_t str2[] = L"Learn wcslen in C";// calculate lengthssize_t len1 = wcslen(str1);size_t len2 = wcslen(str2);// output resultsprintf("\'%ls\' contains %d characters.\n", str1, len1);printf("\'%ls\' contains %d characters.\n", str2, len2);return 0;}
Explanation
First, the code initializes two wide strings. The ‘L’ identifier in lines 7 and 8 informs the compiler that the Unicode character set is being used.
The wcslen function proceeds to find the length of both of these strings in lines 11 and 12, respectively. These lengths are then written to stdout.
Free Resources