名前空間
変種
操作

mbrlen

From cppreference.com
< c‎ | string‎ | multibyte
ヘッダー <wchar.h> で定義
size_t mbrlen( const char* s, size_t n, mbstate_t* ps );
(C95 以降)
(C99まで)
size_t mbrlen( const char* restrict s, size_t n, mbstate_t* restrict ps );
(C99以降)

マルチバイト文字の表現のサイズ(バイト単位)を決定します。

この関数は、ある隠された mbstate_t 型のオブジェクト internal に対して、mbrtowc(NULL, s, n, ps ? ps : &internal) を呼び出すのと同等ですが、式 ps は一度だけ評価されます。

目次

[編集] パラメータ

s - マルチバイト文字文字列の要素へのポインタ
n - 検査できるs内のバイト数の制限
ps - 変換状態を保持する変数へのポインタ

[編集] 戻り値

以下が適用される場合、最初のもの

  • 次の n バイト以下でヌル文字が完成する場合、または s がヌルポインタである場合は 0。どちらの場合も変換状態はリセットされます。
  • 有効なマルチバイト文字を完成させるバイト数 [1...n]
  • (size_t)-2 n バイトすべてを調べても、次の n バイトが(おそらく有効な)マルチバイト文字の一部であり、まだ不完全である場合。
  • (size_t)-1 エンコーディングエラーが発生した場合。 errno の値は EILSEQ に設定されます。変換状態は未指定です。

[編集]

#include <locale.h>
#include <stdio.h>
#include <string.h>
#include <wchar.h>
 
int main(void)
{
    // allow mbrlen() to work with UTF-8 multibyte encoding
    setlocale(LC_ALL, "en_US.utf8");
 
    // UTF-8 narrow multibyte encoding
    const char* str = "水";
    size_t sz = strlen(str);
 
    mbstate_t mb;
    memset(&mb, 0, sizeof mb);
    int len1 = mbrlen(str, 1, &mb);
    if (len1 == -2)
        printf("The first 1 byte of %s is an incomplete multibyte char"
               " (mbrlen returns -2)\n", str);
 
    int len2 = mbrlen(str + 1, sz - 1, &mb);
    printf("The remaining %zu  bytes of %s hold %d bytes of the multibyte"
           " character\n", sz - 1, str, len2);
 
    printf("Attempting to call mbrlen() in the middle of %s while in initial"
           " shift state returns %zd\n", str, mbrlen(str + 1, sz - 1, &mb));
}

出力

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

[編集] 参考文献

  • C23標準 (ISO/IEC 9899:2024)
  • 7.29.6.3.1 The mbrlen function (p: TBD)
  • C17標準 (ISO/IEC 9899:2018)
  • 7.29.6.3.1 The mbrlen function (p: TBD)
  • C11標準 (ISO/IEC 9899:2011)
  • 7.29.6.3.1 The mbrlen function (p: 442)
  • C99標準 (ISO/IEC 9899:1999)
  • 7.24.6.3.1 The mbrlen function (p: 388)

[編集] 関連項目

与えられた状態で、次のマルチバイト文字をワイド文字に変換する
(関数) [編集]
次のマルチバイト文字のバイト数を返す
(関数) [編集]
English 日本語 中文(简体) 中文(繁體)