본문 바로가기

카테고리 없음

utf8 문자 세기

#include <iostream>
#include <string>
#include <string_view>

std::size_t count_utf8_chars(std::string_view s) {
    constexpr unsigned char TOP2BIT_MASK = 0b11000000;        // 상위 2비트만 확인
    constexpr unsigned char continuationBytePrefix = 0b10000000; // "10"으로 시작 → 연속 바이트

    std::size_t count = 0;
    for (unsigned char c : s) {
        // 상위 2비트가 "10"이 아니면 새로운 문자 시작
        if ((c & TOP2BIT_MASK) != continuationBytePrefix)
            ++count;
    }
    return count;
}

int main() {
    std::string text = u8"가A나";
    std::cout << "바이트 수: " << text.size() << '\n';
    std::cout << "문자 수: " << count_utf8_chars(text) << '\n';
}