- C 标准库
- C 库 - 首页
- C 库 - <assert.h>
- C 库 - <complex.h>
- C 库 - <ctype.h>
- C 库 - <errno.h>
- C 库 - <fenv.h>
- C 库 - <float.h>
- C 库 - <inttypes.h>
- C 库 - <iso646.h>
- C 库 - <limits.h>
- C 库 - <locale.h>
- C 库 - <math.h>
- C 库 - <setjmp.h>
- C 库 - <signal.h>
- C 库 - <stdalign.h>
- C 库 - <stdarg.h>
- C 库 - <stdbool.h>
- C 库 - <stddef.h>
- C 库 - <stdio.h>
- C 库 - <stdlib.h>
- C 库 - <string.h>
- C 库 - <tgmath.h>
- C 库 - <time.h>
- C 库 - <wctype.h>
- C 标准库资源
- C 库 - 快速指南
- C 库 - 有用资源
- C 库 - 讨论
C 库 - mblen() 函数
C 的stdlib 库 mblen() 函数用于返回以 'str' 指向的多字节字符的第一个字节开头的多字节字符的长度(以字节为单位)。多字节字符由一个或多个字节的序列组成。
mblen() 的行为取决于当前的区域设置,该区域设置包含语言和编码参数。
语法
以下是 mblen() 函数的 C 库语法 -
int mblen(const char *str, size_t n)
参数
此函数接受以下参数 -
str - 这是指向多字节字符第一个字节的指针。
n - 这是要检查字符长度的最大字节数。
返回值
此函数返回以下值 -
如果 str 不是空指针,则返回从以 str 开头的多字节字符传递的字节数。
如果 str 指向的第一个字节不构成有效的多字节字符,则返回 -1。
如果 str 指向空字符。它返回 0。
示例 1
在此示例中,我们创建一个基本的 c 程序来演示 mblen() 函数的使用。
#include <stdio.h>
#include <stdlib.h>
int main() {
char *mbstr = (char *)malloc(sizeof(char));
int len;
// first reset mblen
mblen(NULL, 0);
mbstr = "tutorialspoint";
// display the length of a multibyte character
len = mblen(mbstr, MB_CUR_MAX);
printf("Length in bytes of multibyte character: %u\n", len);
return 0;
}
输出
以下是输出 -
Length in bytes of multibyte character: 1
示例 2
让我们创建另一个示例,我们使用 mblen() 函数获取多字节字符的长度。如果字符串指向空字符。
#include <stdio.h>
#include <stdlib.h>
int main() {
char *mbstr = (char *)malloc(sizeof(char));
int len;
// first reset mblen
mblen(NULL, 0);
mbstr = NULL;
// display the length of a multibyte character
len = mblen(mbstr, MB_CUR_MAX);
printf("Length in bytes of NULL multibyte character: %u\n", len);
return 0;
}
输出
以下是输出 -
Length in bytes of NULL multibyte character: 0
示例 3
下面的 c 程序获取多字节字符的长度并显示语句。如果字符串是无效的多字节序列。
#include <stdio.h>
#include <stdlib.h>
#include <locale.h>
int main() {
// create an invalid multi-byte sequence
const char *invalidStr = "\xE2\x80";
// Set locale for UTF-8
setlocale(LC_ALL, "en_US.utf8");
// get the lenfth of multi-byte character.
int len = mblen(invalidStr, MB_CUR_MAX);
if (len == -1) {
perror("Invalid multi-byte sequence");
} else {
printf("Length in bytes of invalid multibyte character: %d\n", len);
}
return 0;
}
输出
以下是输出 -
Invalid multi-byte sequence: Invalid or incomplete multibyte or wide character
广告