是否有与char16_t工作的的strlen()? [英] Is there a strlen() that works with char16_t?

查看:1408
本文介绍了是否有与char16_t工作的的strlen()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于这个问题说:

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;
}

我搜索,发现只有C ++的解决方案。

I searched and found only C++ solutions.

我的编译器是 GCC 4.7

编辑:

要澄清,我正在寻找一个返回 $ C $的ç点计数的解决方案,而不是字符计数

To clarify, I was searching for a solution that returns the count of code points, not the count of characters.

这两个是完全不同的 UTF-16 包含之外的字符字符串 BMP

These two are quite different for UTF-16 strings containing characters outside the BMP.

推荐答案

这是你的基本的strlen:

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;
}

下面是一个更有效,更受欢迎的strlen:

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;
}

希望这有助于。

警告:这不正常计数UTF-16字符串的字符(不code点)时工作。当 __ __ STDC_UTF_16 定义为 1 这是尤其如此。

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是可变长度(每个字符2个字节的BMP或每BMP以外的字符4个字节),而没有包括在这些功能。

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.

这篇关于是否有与char16_t工作的的strlen()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆