std::mblen
提供: cppreference.com
ヘッダ <cstdlib> で定義 | ||
int mblen(constchar* s, std::size_t n ); | ||
s
によって最初のバイトが指されているマルチバイト文字のバイト単位のサイズを調べます。
s
がヌルポインタの場合は、グローバルな変換状態をリセットし、シフトシーケンスが使用されるかどうかを調べます。
この関数は std::mbtowc の変換状態が影響を受けないことを除いて std::mbtowc((wchar_t*)0, s, n) の呼び出しと同等です。
目次 |
[編集]ノート
mblen
を呼ぶたびに、内部のグローバルな変換状態 (この関数のみが使用する std::mbstate_t 型の静的オブジェクト) を更新します。 マルチバイトエンコーディングがシフト状態を使用する場合、バックトラッキングや複数回のスキャンを避けるように注意しなければなりません。 いずれの場合でも、複数のスレッドが同期せずに mblen
を呼ぶべきではありません。 代わりに std::mbrlen を使用することができます。
[編集]引数
s | - | マルチバイト文字を指すポインタ |
n | - | 調べることができる s 内のバイト数の制限 |
[編集]戻り値
s
がヌルポインタでなければ、そのマルチバイト文字に含まれるバイト数を返します。 s
の指す最初のバイト列が有効なマルチバイト文字を形成しない場合は -1、 s
がヌル文字 '\0' を指す場合は 0 を返します。
s
がヌルポインタであれば、内部の変換状態を初期シフト状態を表すようにリセットし、現在のマルチバイトエンコーディングが状態依存でない (シフトシーケンスを使用しない) 場合は 0、現在のマルチバイトエンコーディングが状態依存 (シフトシーケンスを使用する) の場合は非ゼロの値を返します。
[編集]例
Run this code
#include <clocale>#include <string>#include <iostream>#include <cstdlib>#include <stdexcept> // the number of characters in a multibyte string is the sum of mblen()'s// note: the simpler approach is std::mbstowcs(NULL, s.c_str(), s.size())std::size_t strlen_mb(conststd::string& s){std::size_t result =0;constchar* ptr = s.data();constchar* end = ptr + s.size(); std::mblen(NULL, 0);// reset the conversion statewhile(ptr < end){int next = std::mblen(ptr, end-ptr);if(next ==-1){throwstd::runtime_error("strlen_mb(): conversion error");} ptr += next;++result;}return result;} int main(){// allow mblen() to work with UTF-8 multibyte encodingstd::setlocale(LC_ALL, "en_US.utf8");// UTF-8 narrow multibyte encodingstd::string str = u8"z\u00df\u6c34\U0001f34c";// or u8"zß水🍌"std::cout<< str <<" is "<< str.size()<<" bytes, but only "<< strlen_mb(str)<<" characters\n";}
出力:
zß水🍌 is 10 bytes, but only 4 characters
[編集]関連項目
次のマルチバイト文字をワイド文字に変換します (関数) | |
指定された状態を使用して次のマルチバイト文字のバイト数を返します (関数) | |
mblen の C言語リファレンス |