查找 std::wstring 的长度 [英] Find length of std::wstring

查看:16
本文介绍了查找 std::wstring 的长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何确定 std::wstring 中的长度(字符数)?

How can I determine the length(number of characters) in a std::wstring?

使用 myStr.length() 给出字节大小(我认为)但不是字符数.我是否需要创建自己的函数来查找字符数或是否有本机 C++ 方式或本机 WinAPI 方式?

Using myStr.length() gives the byte size(I think) but its not the number of characters. Do I need to create my own function to find the number of characters or is there a native C++ way or a native WinAPI way?

推荐答案

std::wstring::length() 会给你字符数,其中 character被定义为wstring 对象的原子单位,即一个wchar.这就是标准在提到 characters 时的意思(请参阅这篇文章了解更多详情关于该词在标准中的使用).

std::wstring::length() will give you the number of characters, where character is defined as the atomic unit of the wstring object, i.e. a wchar. This is what the Standard means when it refers to characters (see this post for some more details on the use of the word in the Standard).

但是,对于Unicode字符,一个wchar是否对应一个Unicode字符取决于wstring内部使用的编码.如果使用 UTF-16,通常(但不一定)是这种情况,一个 wchar 将仅对应于基本多语言平面的一个 Unicode 字符(即所有源自 ISO-8859 的字符集作为以及大多数常用的 CJK 字符,但不包括一些更奇特的(例如文言文)字符)(*).在这种情况下,如果您想获得 所有 Unicode 字符的正确字符数,您需要使用支持 Unicode 的库(例如 ICU),或者自己编写代码.

However, when it comes to Unicode characters, whether one wchar corresponds to one Unicode character depends on the encoding used inside the wstring. If UTF-16 is used, which is often (but not necessarily) the case, one wchar will correspond to one Unicode character only for the base multilingual plane (i.e. all character sets derived from ISO-8859 as well as most of the commonly used CJK characters, but not some of the more exotic (e.g. classical Chinese) characters)(*). If you want to get the character count right for all Unicode characters in that case, you need to use a Unicode-aware library (e.g. ICU), or code it yourself.

(*)如果使用组合字符,还有其他问题,正如@一二三正确指出的那样.最好使用适当的库来正确计算它们.

(*)There are additional problems if combining characters are used, as @一二三 points out correctly. Counting those correctly is also best done using appropriate libraries.

这篇关于查找 std::wstring 的长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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