std::mblen
From cppreference.com
| ヘッダ <cstdlib> で定義 |
||
| int mblen( const char* s, std::size_t n ); |
||
引数 s が指すバイトから始まるマルチバイト文字のバイト数を決定します。
s がヌルポインタの場合、グローバル変換状態をリセットし、シフトシーケンスが使用されているかどうかを判断します。
この関数は、std::mbtowc(nullptr, s, n) の呼び出しと同等ですが、std::mbtowc の変換状態は影響を受けません。
目次 |
[編集] 注釈
mblen の各呼び出しは、内部グローバル変換状態(この関数のみが知る std::mbstate_t 型の静的オブジェクト)を更新します。マルチバイトエンコーディングがシフト状態を使用する場合、後退や複数回のスキャンを避けるために注意が必要です。いずれの場合も、複数のスレッドは同期なしで mblen を呼び出すべきではありません。代わりに std::mbrlen を使用できます。
[編集] パラメータ
| s | - | マルチバイト文字へのポインタ |
| n | - | 検査できるs内のバイト数の制限 |
[編集] 戻り値
s がヌルポインタでない場合、マルチバイト文字に含まれるバイト数、または s が指す最初のバイトが有効なマルチバイト文字を形成しない場合は -1、s がヌル文字 '\0' を指している場合は 0 を返します。
s がヌルポインタの場合、初期シフト状態を表すように内部変換状態をリセットし、現在のマルチバイトエンコーディングが状態依存でない(シフトシーケンスを使用しない)場合は 0 を、状態依存である(シフトシーケンスを使用する)場合はゼロ以外の値を返します。
[編集] 例
このコードを実行
#include <clocale> #include <cstdlib> #include <iomanip> #include <iostream> #include <stdexcept> #include <string_view> // the number of characters in a multibyte string is the sum of mblen()'s // note: the simpler approach is std::mbstowcs(nullptr, s.c_str(), s.size()) std::size_t strlen_mb(const std::string_view s) { std::mblen(nullptr, 0); // reset the conversion state std::size_t result = 0; const char* ptr = s.data(); for (const char* const end = ptr + s.size(); ptr < end; ++result) { const int next = std::mblen(ptr, end - ptr); if (next == -1) throw std::runtime_error("strlen_mb(): conversion error"); ptr += next; } return result; } void dump_bytes(const std::string_view str) { std::cout << std::hex << std::uppercase << std::setfill('0'); for (unsigned char c : str) std::cout << std::setw(2) << static_cast<int>(c) << ' '; std::cout << std::dec << '\n'; } int main() { // allow mblen() to work with UTF-8 multibyte encoding std::setlocale(LC_ALL, "en_US.utf8"); // UTF-8 narrow multibyte encoding const std::string_view str = "z\u00df\u6c34\U0001f34c"; // or u8"zß水🍌" std::cout << std::quoted(str) << " is " << strlen_mb(str) << " characters, but as much as " << str.size() << " bytes: "; dump_bytes(str); }
実行結果の例
"zß水🍌" is 4 characters, but as much as 10 bytes: 7A C3 9F E6 B0 B4 F0 9F 8D 8C
[編集] 関連項目
| 次のマルチバイト文字をワイド文字に変換する (関数) | |
| 与えられた状態で、次のマルチバイト文字のバイト数を返す (関数) | |
| C言語ドキュメント ( mblen )
| |