名前空間
変種
操作

std::mbrlen

提供: cppreference.com
< cpp‎ | string‎ | multibyte
ヘッダ <cwchar> で定義
std::size_t mbrlen( const char* s, std::size_t n, std::mbstate_t* ps);

現在の変換状態 ps において、最初のバイトが s によって指されているマルチバイト文字の残りのバイト単位のサイズを調べます。

この関数は、式 ps が一度しか評価されないことを除き、 std::mbstate_t 型の何らかの隠れたオブジェクト internal に対する呼び出し std::mbrtowc(nullptr, s, n, ps?ps:&internal) と同等です。

目次

[編集] 引数

s - マルチバイト文字列の要素を指すポインタ
n - 調べる s のバイト数の制限
ps - 変換状態を保持する変数を指すポインタ

[編集] 戻り値

次の n バイトまたはそれより少ないバイトが完全なヌル文字を構成する場合は 0

有効なマルチバイト文字を構成するバイト数 (1n の間)。

エンコーディングエラーが発生した場合は (size_t)-1

次の n バイトが有効なマルチバイト文字となり得る一部だけれども、 n バイトをすべて調べた後未だ不完全な場合は (size_t)-2

[編集]

#include <clocale>
#include <string>
#include <iostream>
#include <cwchar>
 
int main()
{
    // allow mbrlen() to work with UTF-8 multibyte encoding
    std::setlocale(LC_ALL, "en_US.utf8");
    // UTF-8 narrow multibyte encoding
    std::string str = u8"水"; // or u8"\u6c34" or "\xe6\xb0\xb4"
    std::mbstate_t mb = std::mbstate_t();
    int len1 = std::mbrlen(&str[0], 1, &mb);
    if(len1 == -2) {
        std::cout << "The first 1 byte of " << str
                  << " is an incomplete multibyte char (mbrlen returns -2)\n";
    }
    int len2 = std::mbrlen(&str[1], str.size()-1, &mb);
    std::cout << "The remaining " << str.size()-1 << " bytes of " << str
              << " hold " << len2 << " bytes of the multibyte character\n";
    std::cout << "Attempting to call mbrlen() in the middle of " << str
              << " while in initial shift state returns "
              << (int)mbrlen(&str[1], str.size(), &mb) << '\n';
 
}

出力:

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

[編集] 関連項目

指定された状態を使用して次のマルチバイト文字をワイド文字に変換します
(関数) [edit]
次のマルチバイト文字のバイト数を返します
(関数) [edit]
[仮想]
与えられた internT バッファへの変換によって消費されるであろう externT 文字列の長さを計算します
(std::codecvt<InternT,ExternT,State>の仮想プロテクテッドメンバ関数) [edit]