mblen
提供: cppreference.com
ヘッダ <stdlib.h> で定義 | ||
int mblen(constchar* s, size_t n ); | ||
s
によって最初のバイトが指されているマルチバイト文字のバイト単位のサイズを調べます。
s
がヌルポインタの場合は、グローバルな変換状態をリセットし、シフトシーケンスが使用されるかどうかを調べます。
この関数は mbtowc の変換状態が影響を受けないことを除いて mbtowc((wchar_t*)0, s, n) の呼び出しと同等です。
目次 |
[編集]ノート
mblen
を呼ぶたびに、内部のグローバルな変換状態 (この関数のみが使用する mbstate_t 型の静的オブジェクト) を更新します。 マルチバイトエンコーディングがシフト状態を使用する場合、バックトラッキングや複数回のスキャンを避けるように注意しなければなりません。 いずれの場合でも、複数のスレッドが同期せずに mblen
を呼ぶべきではありません。 代わりに mbrlen を使用することができます。
[編集]引数
s | - | マルチバイト文字を指すポインタ |
n | - | 調べることができる s 内のバイト数の制限 |
[編集]戻り値
s
がヌルポインタでなければ、そのマルチバイト文字に含まれるバイト数を返します。 s
の指す最初のバイト列が有効なマルチバイト文字を形成しない場合は -1、 s
がヌル文字 '\0' を指す場合は 0 を返します。
s
がヌルポインタであれば、内部の変換状態を初期シフト状態を表すようにリセットし、現在のマルチバイトエンコーディングが状態依存でない (シフトシーケンスを使用しない) 場合は 0、現在のマルチバイトエンコーディングが状態依存 (シフトシーケンスを使用する) の場合は非ゼロの値を返します。
[編集]例
Run this code
#include <string.h>#include <stdlib.h>#include <locale.h>#include <stdio.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(constchar* ptr){size_t result =0;constchar* end = ptr +strlen(ptr); mblen(NULL, 0);// reset the conversion statewhile(ptr < end){int next = mblen(ptr, end - ptr);if(next ==-1){perror("strlen_mb");break;} ptr += next;++result;}return result;} int main(void){setlocale(LC_ALL, "en_US.utf8");constchar* str ="z\u00df\u6c34\U0001f34c";printf("The string %s consists of %zu bytes, but only %zu characters\n", str, strlen(str), strlen_mb(str));}
出力例:
The string zß水🍌 consists of 10 bytes, but only 4 characters
[編集]参考文献
- C11 standard (ISO/IEC 9899:2011):
- 7.22.7.1 The mblen function (p: 357)