命名空间
变体
操作

std::mbrlen

来自 cppreference.cn
< cpp‎ | string‎ | multibyte
定义于头文件 <cwchar>
std::size_t mbrlen( const char* s, std::size_t n, std::mbstate_t* ps);

确定以字节为单位的多字节字符的剩余大小,该多字节字符的第一个字节由 s 指向,并给定当前的转换状态 ps

此函数等效于调用 std::mbrtowc(nullptr, s, n, ps ? ps : &internal) 对于某些类型为 std::mbstate_t 的隐藏对象 internal,除了表达式 ps 只被评估一次。

目录

[edit] 参数

s - 指向多字节字符串元素的指针
n - 可以检查的 s 中的字节数限制
ps - 指向保存转换状态的变量的指针

[edit] 返回值

  • 0 如果接下来的 n 个或更少的字节完成空字符。
  • 完成有效多字节字符的字节数(介于 1n 之间)。
  • std::size_t(-1) 如果发生编码错误。
  • std::size_t(-2) 如果接下来的 n 个字节是可能有效的多字节字符的一部分,但在检查所有 n 个字节后仍然不完整。

[edit] 示例

#include <clocale>
#include <cwchar>
#include <iostream>
#include <string>
 
int main()
{
    // allow mbrlen() to work with UTF-8 multibyte encoding
    std::setlocale(LC_ALL, "en_US.utf8");
 
    // UTF-8 narrow multibyte encoding
    std::string str = "水"; // or u8"\u6c34" or "\xe6\xb0\xb4"
    std::mbstate_t mb = std::mbstate_t();
 
    // simple use: length of a complete multibyte character
    const std::size_t len = std::mbrlen(&str[0], str.size(), &mb);
    std::cout << "The length of " << str << " is " << len << " bytes\n";
 
    // advanced use: restarting in the middle of a multibyte character
    const std::size_t len1 = std::mbrlen(&str[0], 1, &mb);
    if (len1 == std::size_t(-2))
        std::cout << "The first 1 byte of " << str
                  << " is an incomplete multibyte char (mbrlen returns -2)\n";
 
    const std::size_t len2 = std::mbrlen(&str[1], str.size() - 1, &mb);
    std::cout << "The remaining " << str.size() - 1 << " bytes of " << str
              << " hold " << len2 << " bytes of the multibyte character\n";
 
    // error case:
    std::cout << "Attempting to call mbrlen() in the middle of " << str
              << " while in initial shift state returns "
              << (int)mbrlen(&str[1], str.size(), &mb) << '\n';
}

输出

The length of 水 is 3 bytes.
The first 1 byte of 水 is an incomplete multibyte char (mbrlen returns -2)
The remaining 2 bytes of 水 hold 2 bytes of the multibyte character
Attempting to call mbrlen() in the middle of 水 while in initial shift state returns -1

[edit] 参见

将下一个多字节字符转换为宽字符,给定状态
(函数) [edit]
返回下一个多字节字符中的字节数
(函数) [edit]
[virtual]
计算将被转换为给定 InternT 缓冲区的 ExternT 字符串的长度
(std::codecvt<InternT,ExternT,StateT> 的虚保护成员函数) [edit]
C 文档 关于 mbrlen