名稱空間
變體
操作

std::mblen

來自 cppreference.com
< cpp‎ | string‎ | multibyte
定義於標頭檔案 <cstdlib>
int mblen( const char* s, std::size_t n );

確定多位元組字元的位元組大小,其首位元組由 s 指向。

如果 s 是空指標,則重置全域性轉換狀態並確定是否使用移位序列。

此函式等價於呼叫 std::mbtowc(nullptr, s, n),除了 std::mbtowc 的轉換狀態不受影響。

目錄

[編輯] 注意

每次呼叫 mblen 都會更新內部全域性轉換狀態(一個型別為 std::mbstate_t 的靜態物件,僅此函式可見)。如果多位元組編碼使用移位狀態,則必須注意避免回溯或多次掃描。在任何情況下,多個執行緒都不應在沒有同步的情況下呼叫 mblen:可以改用 std::mbrlen

[編輯] 引數

s - 指向多位元組字元的指標
n - s 中可檢查的位元組數的限制

[編輯] 返回值

如果 s 不是空指標,則返回多位元組字元中包含的位元組數,如果 s 指向的第一個位元組不構成有效的多位元組字元,則返回 -1,如果 s 指向空字元 '\0',則返回 0

如果 s 是空指標,則將其內部轉換狀態重置為表示初始移位狀態,如果當前多位元組編碼與狀態無關(不使用移位序列),則返回 0,如果當前多位元組編碼與狀態相關(使用移位序列),則返回非零值。

[編輯] 示例

#include <clocale>
#include <cstdlib>
#include <iomanip>
#include <iostream>
#include <stdexcept>
#include <string_view>
 
// the number of characters in a multibyte string is the sum of mblen()'s
// note: the simpler approach is std::mbstowcs(nullptr, s.c_str(), s.size())
std::size_t strlen_mb(const std::string_view s)
{
    std::mblen(nullptr, 0); // reset the conversion state
    std::size_t result = 0;
    const char* ptr = s.data();
    for (const char* const end = ptr + s.size(); ptr < end; ++result)
    {
        const int next = std::mblen(ptr, end - ptr);
        if (next == -1)
            throw std::runtime_error("strlen_mb(): conversion error");
        ptr += next;
    }
    return result;
}
 
void dump_bytes(const std::string_view str)
{
    std::cout << std::hex << std::uppercase << std::setfill('0');
    for (unsigned char c : str)
        std::cout << std::setw(2) << static_cast<int>(c) << ' ';
    std::cout << std::dec << '\n';
}
 
int main()
{
    // allow mblen() to work with UTF-8 multibyte encoding
    std::setlocale(LC_ALL, "en_US.utf8");
    // UTF-8 narrow multibyte encoding
    const std::string_view str = "z\u00df\u6c34\U0001f34c"; // or u8"zß水🍌"
    std::cout << std::quoted(str) << " is " << strlen_mb(str)
              << " characters, but as much as " << str.size() << " bytes: ";
    dump_bytes(str);
}

可能的輸出

"zß水🍌" is 4 characters, but as much as 10 bytes: 7A C3 9F E6 B0 B4 F0 9F 8D 8C

[編輯] 另請參閱

將下一個多位元組字元轉換為寬字元
(函式) [編輯]
返回下一個多位元組字元的位元組數,給定狀態
(函式) [編輯]
C 文件 關於 mblen