std::mbrlen
From cppreference.com
| ヘッダ <cwchar> で定義 |
||
| std::size_t mbrlen( const char* s, std::size_t n, std::mbstate_t* ps); |
||
指定された現在の変換状態psにおいて、バイト列sの先頭バイトから始まるマルチバイト文字の残りの部分のバイト数を決定します。
この関数は、ある隠されたstd::mbstate_t型のオブジェクトinternalに対して、std::mbrtowc(nullptr, s, n, ps ? ps : &internal )を呼び出すことと同等ですが、式psは一度だけ評価されます。
目次 |
[編集] パラメータ
| s | - | マルチバイト文字文字列の要素へのポインタ |
| n | - | 検査できるs内のバイト数の制限 |
| ps | - | 変換状態を保持する変数へのポインタ |
[編集] 戻り値
- 0 : 次のnバイト以下でヌル文字が完了する場合。
- 有効なマルチバイト文字を完了するバイト数(1からnの間)。
- std::size_t(-1) : エンコーディングエラーが発生した場合。
- std::size_t(-2) : 次のnバイトが、nバイトすべてを検査した後でも不完全な、おそらく有効なマルチバイト文字の一部である場合。
[編集] 例
このコードを実行
#include <clocale> #include <cwchar> #include <iostream> #include <string> 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 = "水"; // or u8"\u6c34" or "\xe6\xb0\xb4" std::mbstate_t mb = std::mbstate_t(); // simple use: length of a complete multibyte character const std::size_t len = std::mbrlen(&str[0], str.size(), &mb); std::cout << "The length of " << str << " is " << len << " bytes\n"; // advanced use: restarting in the middle of a multibyte character const std::size_t len1 = std::mbrlen(&str[0], 1, &mb); if (len1 == std::size_t(-2)) std::cout << "The first 1 byte of " << str << " is an incomplete multibyte char (mbrlen returns -2)\n"; const std::size_t 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"; // error case: 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 length of 水 is 3 bytes. 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
[編集] 関連項目
| 与えられた状態で、次のマルチバイト文字をワイド文字に変換する (関数) | |
| 次のマルチバイト文字のバイト数を返す (関数) | |
| [virtual] |
指定された InternT バッファへの変換によって消費される ExternT 文字列の長さを計算します。( std::codecvt<InternT,ExternT,StateT> の virtual protected メンバ関数) |
| C言語ドキュメント (mbrlen)
| |