mblen
From cppreference.com
| ヘッダー <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 を返し、状態に依存する(シフトシーケンスを使用する)場合は非ゼロ値を返します。
[編集] 注記
|
|
(C23まで) |
|
|
(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 The mblen function (p: 260)
- C11標準 (ISO/IEC 9899:2011)
- 7.22.7.1 The mblen function (p: 357)
- C99標準 (ISO/IEC 9899:1999)
- 7.20.7.1 The mblen function (p: 321)
- C89/C90標準 (ISO/IEC 9899:1990)
- 4.10.7.1 The mblen function
[編集] 関連項目
| 次のマルチバイト文字をワイド文字に変換する (関数) | |
| (C95) |
与えられた状態で、次のマルチバイト文字のバイト数を返す (関数) |
| C++ ドキュメント for mblen
| |