名稱空間
變體
操作

std::mbrlen

來自 cppreference.com
< cpp‎ | string‎ | multibyte
在標頭檔案 <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 個或更少位元組構成空字元。
  • 構成一個有效多位元組字元的位元組數(介於 1n 之間)。
  • std::size_t(-1) 如果發生編碼錯誤。
  • std::size_t(-2) 如果接下來的 n 個位元組是一個可能有效的多位元組字元的一部分,但在檢查所有 n 個位元組後仍不完整。

[編輯] 示例

#include <clocale>
#include <cwchar>
#include <iostream>
#include <string>
 
int main()
{
    // allow mbrlen() to work with UTF-8 multibyte encoding
    std::setlocale(LC_ALL, "en_US.utf8");
 
    // UTF-8 narrow multibyte encoding
    std::string str = "水"; // or u8"\u6c34" or "\xe6\xb0\xb4"
    std::mbstate_t mb = std::mbstate_t();
 
    // simple use: length of a complete multibyte character
    const std::size_t len = std::mbrlen(&str[0], str.size(), &mb);
    std::cout << "The length of " << str << " is " << len << " bytes\n";
 
    // advanced use: restarting in the middle of a multibyte character
    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";
 
    // error case:
    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

[編輯] 參見

將下一個多位元組字元轉換為寬字元,給定狀態
(function) [編輯]
返回下一個多位元組字元的位元組數
(function) [編輯]
[virtual]
計算轉換為給定 InternT 緩衝區時將消耗的 ExternT 字串的長度
(std::codecvt<InternT,ExternT,StateT> 的虛保護成員函式) [編輯]
有關 mbrlenC 文件