std::mblen
cppreference.com
<tbody>
</tbody>
int mblen( const char* s, std::size_t n ); |
||
, s.
s , , .
std::mbtowc((wchar_t*)0, s, n), , std::mbtowc .
mblen ( std::mbstate_t, ). , . mblen : std::mbrlen.
| s | ||
| n | s, |
s , , , -1, , s, 0, s '\0'.
s , , , 0, ( ) , ( ).
#include <clocale>
#include <cstdlib>
#include <iomanip>
#include <iostream>
#include <stdexcept>
#include <string_view>
// mblen()
// :
// std::mbstowcs(nullptr, s.c_str(), s.size())
std::size_t strlen_mb(const std::string_view s)
{
std::mblen(nullptr, 0); //
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(): ");
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()
{
// mblen() UTF-8
std::setlocale(LC_ALL, "en_US.utf8");
// UTF-8
const std::string_view str = "z\u00df\u6c34\U0001f34c"; // u8"z"
std::cout << std::quoted(str) << " " << strlen_mb(str)
<< " , " << str.size() << " : ";
dump_bytes(str);
}
:
"z" 4 , 10 : 7A C3 9F E6 B0 B4 F0 9F 8D 8C
| () | |
| () | |
C mblen
| |