Search code examples
widestring

Finding length of wide character strings


To find the length of non wide character strings we use the strlen function:

#include <stdio.h>
#include <wchar.h>
#include <string.h>

int main(void)
{
char variable1[50] = "This is a test sent";
printf("The length of the string is: %d", strlen(variable1));
return 0;
}  
OUTPUT: 
The length of the string is: 18

All my book says is to use the syntax:

wcslen(const wchar_t* ws)

But, I've tried a number of ways to do so but it never works:

USING THE D FORMAT SPECIFIER:

#include <stdio.h>
#include <wchar.h>
int main(void)
{
wchar_t variable1[50] = "This is a test sent";
printf("The length of the string is: %d", wcslen(const wchar_t* variable1));
return 0;
}  

USING THE U FORMAT SPECIFIER

#include <stdio.h>
#include <wchar.h>

int main(void)
{
wchar_t variable[50] = "This is a test sent";
printf("The length of the string is: %u", wcslen(variable1));
return 0;
}  

USING A VARIABLE OF TYPE SIZE_T

#include <stdio.h>
#include <wchar.h>

int main(void)
{
wchar_t variable1[50] = "This is a test sent";
size_t variable2 = wcslen(char wchar_t* variable1);
printf("The length of the string is: %u", variable2);
return 0;
}  

How do we find the length of the string so that we get an output similar to the first?(All of the last three codes produce an error)


Solution

  • To initiate a wide character string ypu have to prefix "L" before the string like :

    wchar_t variable1[50] = L"This is a test sent";
    

    This would make it a "wide" character string.