IsUtf8() - 문자열이 Utf8인지 체크하는 함수
c & c++
2013. 8. 6. 12:28
[-] Collapse
전체 문자열을 검사하여 한 문자열이라도 utf8 코드가 들어 있는 경우 true를 리턴
bool IsUtf8(const char* str)
{
int str_bytes = 0;
if(str == NULL ) {
return false;
}
str_bytes = (int)strlen(str);
bool isUtf8(true);
int index = 0;
while (index < str_bytes && isUtf8)
{
char achar = str[index];
int supplemental_bytes = 0;
if ((achar & 0x80) == 0) {
// 0xxxxxxx
++index;
}
else if ((achar & 0xF8) == 0xF0) {
// 11110uuu 10uuzzzz 10yyyyyy 10xxxxxx
++index;
supplemental_bytes = 3;
}
else if ((achar & 0xE0) == 0xE0) {
// 1110zzzz 10yyyyyy 10xxxxxx
++index;
supplemental_bytes = 2;
}
else if ((achar & 0xE0) == 0xC0) {
// 110yyyyy 10xxxxxx
++index;
supplemental_bytes = 1;
}
else {
isUtf8 = false;
}
while (isUtf8 && supplemental_bytes--)
{
if (index >= str_bytes) {
isUtf8 = false;
}
else if ((str[index++] & 0xC0) != 0x80) {
// 10uuzzzz
isUtf8 = false;
}
}
}
return isUtf8;
}
bool IsUtf8(const char* str)
{
int str_bytes = 0;
if(str == NULL ) {
return false;
}
str_bytes = (int)strlen(str);
bool isUtf8(true);
int index = 0;
while (index < str_bytes && isUtf8)
{
char achar = str[index];
int supplemental_bytes = 0;
if ((achar & 0x80) == 0) {
// 0xxxxxxx
++index;
}
else if ((achar & 0xF8) == 0xF0) {
// 11110uuu 10uuzzzz 10yyyyyy 10xxxxxx
++index;
supplemental_bytes = 3;
}
else if ((achar & 0xE0) == 0xE0) {
// 1110zzzz 10yyyyyy 10xxxxxx
++index;
supplemental_bytes = 2;
}
else if ((achar & 0xE0) == 0xC0) {
// 110yyyyy 10xxxxxx
++index;
supplemental_bytes = 1;
}
else {
isUtf8 = false;
}
while (isUtf8 && supplemental_bytes--)
{
if (index >= str_bytes) {
isUtf8 = false;
}
else if ((str[index++] & 0xC0) != 0x80) {
// 10uuzzzz
isUtf8 = false;
}
}
}
return isUtf8;
}
'c & c++' 카테고리의 다른 글
10년 만에 새로 태어나는 ‘모던 C++’ (0) | 2014.11.04 |
---|---|
안전한 문자열 함수들 (0) | 2013.05.03 |
extern "C" 에 관하여... (0) | 2013.04.16 |