mblen
来自cppreference.com
在标头 <stdlib.h> 定义 | ||
int mblen(constchar* s, size_t n ); | ||
确定 s
指向其首字节的多字节字符的字节大小。
若 s
是空指针,则重置全局转换状态并(C23 前)确定是否使用迁移序列。
此函数等价于调用 mbtowc((wchar_t*)0, s, n),除了 mbtowc 的转换状态不受影响。
目录 |
[编辑]参数
s | - | 指向多字节字符的指针 |
n | - | s 中能被检验的字节数限制 |
[编辑]返回值
若 s
不是空指针,则返回多字节字符所含的字节数,或若 s
所指的首字节不组成合法多字节字符则返回 -1,或若 s
指向空字符 '\0' 则返回 0。
若 s
是空指针,则重置内部转换状态为初始迁移状态,(C23 前)若当前多字节编码非状态依赖(不使用迁移序列)则返回 0,或者若当前多字节编码为状态依赖(使用迁移序列)则返回非零。
[编辑]注解
每次对 | (C23 前) |
不允许 | (C23 起) |
[编辑]示例
运行此代码
#include <locale.h>#include <stdio.h>#include <stdlib.h>#include <string.h> // 多字节字符串的字符数是 mblen() 的和// 注意:更简单的手段是 mbstowcs(NULL, str, sz)size_t strlen_mb(constchar* ptr){size_t result =0;constchar* end = ptr +strlen(ptr); mblen(NULL, 0);// 重置转换状态while(ptr < end){int next = mblen(ptr, end - ptr);if(next ==-1){perror("strlen_mb");break;} ptr += next;++result;}return result;} void dump_bytes(constchar* str){for(constchar* end = str +strlen(str); str != end;++str)printf("%02X ", (unsignedchar)str[0]);printf("\n");} int main(void){setlocale(LC_ALL, "en_US.utf8");constchar* str ="z\u00df\u6c34\U0001f34c";printf("字符串 \"%s\" 包含 %zu 个字符,但为 %zu 字节:", str, strlen_mb(str), strlen(str)); dump_bytes(str);}
可能的输出:
字符串 "zß水🍌" 包含 4 个字符,但为 10 字节:7A C3 9F E6 B0 B4 F0 9F 8D 8C
[编辑]引用
- C17 标准(ISO/IEC 9899:2018):
- 7.22.7.1 The mblen function (第 260 页)
- C11 标准(ISO/IEC 9899:2011):
- 7.22.7.1 The mblen function (第 357 页)
- C99 标准(ISO/IEC 9899:1999):
- 7.20.7.1 The mblen function (第 321 页)
- C89/C90 标准(ISO/IEC 9899:1990):
- 4.10.7.1 The mblen function
[编辑]参阅
转换下一个多字节字符为宽字符 (函数) | |
(C95) | 给定状态,返回下一个多字节字符的字节数 (函数) |
mblen 的 C++ 文档 |