📜  C / C++中的mbrlen()函数

📅  最后修改于: 2021-05-30 03:54:18             🧑  作者: Mango

在给定当前转换状态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. 完成有效的多字节字符的字节数
  2. 如果发生编码错误,则为-1
  3. 如果s指向空字符,则为0
  4. -2如果接下来的n个字节是可能有效的多字节字符,则在检查所有n个字节后仍不完整

下面的程序说明了上述函数:
程序1:

// C++ program to illustrate
// mbrlen() function
#include 
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 
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的C基础课程》。