C ++ std :: string的长度,以字节为单位

Length of a C++ std::string in bytes

我在弄清楚std::string.length()的确切语义时遇到了一些麻烦。
文档明确指出length()返回字符串中的字符数而不是字节数。 我想知道在哪些情况下这实际上有所作为。

特别是,这只与std::basic_string<>的非char实例有关,还是在存储带有多字节字符的UTF-8字符串时也会遇到麻烦? 标准是否允许length()支持UTF8?


在处理std::basic_string<>的非char实例化时,确定,长度可能不等于字节数。对于std::wstring,这一点尤其明显:

1
2
std::wstring ws = L"hi";
cout << ws.length();     // <-- 2, not 4

std::string约为char个字符;就std::string而言,没有多字节字符这样的东西,无论你是否在高级别中填充了一个字符。因此,std::string.length()始终是字符串表示的字节数。请注意,如果您将多字节"字符"填入std::string,那么您对"字符"的定义会突然变得与容器和标准的定义不一致。


如果我们专门讨论std::string,那么length()会返回字节数。

这是因为std::stringcharbasic_string,而C ++标准将一个char的大小定义为恰好一个字节。

请注意,标准没有说明一个字节中有多少位,但这完全是另一个故事,你可能并不在乎。

编辑:标准确实说实现应提供CHAR_BIT的定义,该定义表示一个字节中有多少位。

顺便说一句,如果你沿着一条道路走,你在乎一个字节中有多少位,你可以考虑阅读它。


A std::stringstd::basic_string,所以s.length() * sizeof(char) = byte length。此外,std::string对UTF-8一无所知,所以即使那不是你真正想要的东西,你也会得到字节大小。

如果您在std::string中有UTF-8数据,则需要使用其他内容(如ICU)来获得"实际"长度。


cplusplus.com不是std::string的"文档",它是一个质量低劣的信息质量低劣的网站。 C ++标准非常清楚地定义它:

  • 21.1 [strings.general]?1

    This Clause describes components for manipulating sequences of any non-array POD (3.9) type. In this Clause such types are called char-like types, and objects of char-like types are called char-like objects or simply characters.

  • 21.4.4 [string.capacity]?1

    size_type size() const noexcept;
    Returns: A count of the number of char-like objects currently in the string.
    Complexity: constant time.

    size_type length() const noexcept;
    Returns: size()