Is there a strlen() that works with char16_t?

c, c11, unicode

Solution

Here's your basic strlen:

int strlen16(const char16_t* strarg)
{
   int count = 0;
   if(!strarg)
     return -1; //strarg is NULL pointer
   char16_t* str = strarg;
   while(*str)
   {
      count++;
      str++;
   }
   return count;
}

Here's a more efficient and popular strlen:

int strlen16(const char16_t* strarg)
{
   if(!strarg)
     return -1; //strarg is NULL pointer
   char16_t* str = strarg;
   for(;*str;++str)
     ; // empty body
   return str-strarg;
}

Hope this helps.

Warning: This doesn't work properly when counting the characters (not code points) of a UTF-16 string. This is especially true when `__STDC_UTF_16__` is defined to `1`.

UTF-16 is variable length (2 bytes per character in the BMP or 4 bytes per character outside the BMP) and that is not covered by these functions.

Problem

As the question says: ``` typedef __CHAR16_TYPE__ char16_t; int main(void) { static char16_t test[] = u"Hello World!\n"; printf("Length = %d", strlen(test)); // strlen equivalent for char16_t ??? return 0; } ``` I searched and found only C++ solutions. My compiler is `GCC 4.7`. Edit: To clarify, I was searching for a solution that returns the count of `code points`, not the count of `characters`. These two are quite different for `UTF-16` strings containing characters outside the `BMP`.

Original source

Related problems