在给定当前转换状态ps的情况下,C /C++中的mbrlen()函数确定多字节字符的剩余部分的大小(以字节为单位),该字符的第一个字节由str指向。此函数的行为取决于所选C语言环境的LC_CTYPE类别。
用法:
size_t mbrlen( const char* str, size_t n, mbstate_t* ps)
参数:该函数接受三个强制性参数,如下所述:
- str: 指定指向要检查的多字节字符串的第一个字节的指针
- n: 指定要检查的s中的最大字节数
- ps: 指定指向mbstate_t对象的指针,该对象定义了转换状态
返回值:该函数返回四个值,如下所示:
- 完成有效的多字节字符的字节数
- 如果发生编码错误,则为-1
- 如果s指向空字符,则为0
- -2如果接下来的n个字节是可能有效的多字节字符的一部分,则在检查所有n个字节后仍不完整
以下示例程序旨在说明上述函数:
示例1:
// C++ program to illustrate
// mbrlen() function
#include <bits/stdc++.h>
using namespace std;
// Function to find the size of
// the multibyte character
void check_(const char* str, size_t n)
{
// Multibyte conversion state
mbstate_t ps = mbstate_t();
// number of byte to be saved in returnV
int returnV = mbrlen(str, n, &ps);
if (returnV == -2)
cout << "Next " << n << " byte(s) doesn't"
<< " represent a complete"
<< " multibyte character" << endl;
else if (returnV == -1)
cout << "Next " << n << " byte(s) doesn't "
<< "represent a valid multibyte character" << endl;
else
cout << "Next " << n << " byte(s) of "
<< str << "holds " << returnV << " byte"
<< " multibyte character" << endl;
}
// Driver code
int main()
{
setlocale(LC_ALL, "en_US.utf8");
char str[] = "\u10000b5";
// test for first 1 byte
check_(str, 1);
// test for first 6 byte
check_(str, 6);
return 0;
}
输出:
Next 1 byte(s) doesn't represent a complete multibyte character Next 6 byte(s) of á??0b5holds 3 byte multibyte character
示例2:
// C++ program to illustrate
// mbrlen() function
// with empty string
#include <bits/stdc++.h>
using namespace std;
// Function to find the size of the multibyte character
void check_(const char* str, size_t n)
{
// Multibyte conversion state
mbstate_t ps = mbstate_t();
// number of byte to be saved in returnV
int returnV = mbrlen(str, n, &ps);
if (returnV == -2)
cout << "Next " << n << " byte(s) doesn't"
<< " represent a complete"
<< " multibyte character" << endl;
else if (returnV == -1)
cout << "Next " << n << " byte(s) doesn't "
<< "represent a valid multibyte character" << endl;
else
cout << "Next " << n << " byte(s) of "
<< str << "holds " << returnV << " byte"
<< " multibyte character" << endl;
}
// Driver code
int main()
{
setlocale(LC_ALL, "en_US.utf8");
char str[] = "";
// test for first 1 byte
check_(str, 1);
// test for first 3 byte
check_(str, 3);
return 0;
}
输出:
Next 1 byte(s) of holds 0 byte multibyte character Next 3 byte(s) of holds 0 byte multibyte character
相关用法
- C++ log()用法及代码示例
- C++ div()用法及代码示例
- C++ fma()用法及代码示例
- C++ map key_comp()用法及代码示例
- C++ real()用法及代码示例
- C++ imag()用法及代码示例
- C++ valarray pow()用法及代码示例
- C++ regex_iterator()用法及代码示例
- C++ valarray log()用法及代码示例
注:本文由纯净天空筛选整理自AmanSrivastava1大神的英文原创作品 mbrlen() function in C/C++。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。