std:: mbrlen
From cppreference.net
|
定义于头文件
<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 个或更少字节可补全空字符。
- 返回构成有效多字节字符的字节数(范围在 1 到 n 之间)。
- std:: size_t ( - 1 ) 若出现编码错误。
- std:: size_t ( - 2 ) 若接下来的 n 字节属于可能有效的多字节字符,但在检查全部 n 字节后该字符仍不完整。
示例
运行此代码
#include <clocale> #include <cwchar> #include <iostream> #include <string> int main() { // 允许 mbrlen() 使用 UTF-8 多字节编码 std::setlocale(LC_ALL, "en_US.utf8"); // UTF-8 窄多字节编码 std::string str = "水"; // 或 u8"\u6c34" 或 "\xe6\xb0\xb4" std::mbstate_t mb = std::mbstate_t(); // 简单用法:完整多字节字符的长度 const std::size_t len = std::mbrlen(&str[0], str.size(), &mb); std::cout << "The length of " << str << " is " << len << " bytes\n"; // 高级用法:在多字节字符中间重新开始 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"; // 错误情况: 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
参见
|
在给定状态下将下一个多字节字符转换为宽字符
(函数) |
|
|
返回下一个多字节字符的字节数
(函数) |
|
|
[virtual]
|
计算转换为给定
InternT
缓冲区时将消耗的
ExternT
字符串长度
(
std::codecvt<InternT,ExternT,StateT>
的虚受保护成员函数)
|
|
C 文档
for
mbrlen
|
|