名稱空間
變體
操作

mblen

來自 cppreference.com
< c‎ | string‎ | multibyte
在標頭檔案 <stdlib.h> 中定義
int mblen( const char* s, size_t n );

確定其首位元組由 s 指向的多位元組字元的大小(以位元組為單位)。

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

此函式等價於呼叫 mbtowc((wchar_t*)0, s, n),但 mbtowc 的轉換狀態不受影響。

目錄

[編輯] 引數

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

[編輯] 返回值

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

如果 s 是空指標,則將其內部轉換狀態重置為初始移位狀態,並(直到 C23) 返回 0,如果當前多位元組編碼不依賴於狀態(不使用移位序列),或者返回非零值,如果當前多位元組編碼依賴於狀態(使用移位序列)。

[編輯] 注意

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

(直至 C23)

mblen 不允許有內部狀態。

(自 C23 起)

[編輯] 示例

#include <locale.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
// the number of characters in a multibyte string is the sum of mblen()'s
// note: the simpler approach is mbstowcs(NULL, str, sz)
size_t strlen_mb(const char* ptr)
{
    size_t result = 0;
    const char* end = ptr + strlen(ptr);
    mblen(NULL, 0); // reset the conversion state
    while(ptr < end) {
        int next = mblen(ptr, end - ptr);
        if (next == -1) {
           perror("strlen_mb");
           break;
        }
        ptr += next;
        ++result;
    }
    return result;
}
 
void dump_bytes(const char* str)
{
    for (const char* end = str + strlen(str); str != end; ++str)
        printf("%02X ", (unsigned char)str[0]);
    printf("\n");
}
 
int main(void)
{
    setlocale(LC_ALL, "en_US.utf8");
    const char* str = "z\u00df\u6c34\U0001f34c";
    printf("The string \"%s\" consists of %zu characters, but %zu bytes: ",
            str, strlen_mb(str), strlen(str));
    dump_bytes(str);
}

可能的輸出

The string "zß水🍌" consists of 4 characters, but 10 bytes: 7A C3 9F E6 B0 B4 F0 9F 8D 8C

[編輯] 參考

  • C17 標準 (ISO/IEC 9899:2018)
  • 7.22.7.1 mblen 函式 (p: 260)
  • C11 標準 (ISO/IEC 9899:2011)
  • 7.22.7.1 mblen 函式 (p: 357)
  • C99 標準 (ISO/IEC 9899:1999)
  • 7.20.7.1 mblen 函式 (p: 321)
  • C89/C90 標準 (ISO/IEC 9899:1990)
  • 4.10.7.1 mblen 函式

[編輯] 另請參閱

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