命名空间
变体
操作

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),其中 internal 是类型为 std::mbstate_t 的某个隐藏对象,但表达式 ps 只计算一次。

目录

[编辑] 参数

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

[编辑] 返回值

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

[编辑] 示例

#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

[编辑] 参见

将下一个多字节字符转换为宽字符,给定状态
(function) [编辑]
返回下一个多字节字符的字节数
(function) [编辑]
[virtual]
计算转换为给定 InternT 缓冲区时将消耗的 ExternT 字符串的长度
(std::codecvt<InternT,ExternT,StateT> 的虚保护成员函数) [编辑]
有关 mbrlenC 文档