2010-06-07 1 views
4

다른 사람이 악센트 부호를 제거하기 위해 (예 : 악센트, 움라우트 등이있는 악센트 부호가없는 악센트 부호가없는 악센트 등 모든 악센트와 같은 문자로 대체 할 수있는 몇 가지 샘플 코드를 제공하십시오. éUnicodeString에서 C++의 ICU 라이브러리를 사용하여 일반 ASCII e이됩니까? 예 :ICU를 사용하여 분음 부호를 제거하는 코드

UnicodeString strip_diacritics(UnicodeString const &s) { 
    UnicodeString result; 
    // ... 
    return result; 
} 

s은 이미 표준화되었다고 가정합니다. 감사. 더 다른 검색 후

+1

중복의 : http://stackoverflow.com/questions/331279/how-to-change-diacritic-characters -to-diacritic-ones? –

+0

해당 질문이나 주어진 대답 모두 ICU 라이브러리를 사용하지 않습니다. –

+1

그래서 뭐? 필수 단계는 문자열을 분해 한 다음 분음 부호를 필터링하는 것입니다. Normalizer2 클래스를 사용하십시오. –

답변

-1

:

O (N)이다
UErrorCode status = U_ZERO_ERROR; 
UnicodeString result; 

// 's16' is the UTF-16 string to have diacritics removed 
Normalizer::normalize(s16, UNORM_NFKD, 0, result, status); 
if (U_FAILURE(status)) 
    // complain 

// code to convert UTF-16 's16' to UTF-8 std::string 's8' elided 

string buf8; 
buf8.reserve(s8.length()); 
for (string::const_iterator i = s8.begin(); i != s8.end(); ++i) { 
    char const c = *i; 
    if (isascii(c)) 
    buf8.push_back(c); 
} 
// result is in buf8 

.

+3

ASCII 이외의 문자는 사용하지 않으려 고합니다. 이 코드는 몇 가지 언어로만 작동합니다. –

14

ICU를 사용하면 특정 규칙을 사용하여 문자열을 음역 할 수 있습니다. 내 규칙은 NFD; [:M:] Remove; NFC입니다 : 분해하고, 발음 구별을 제거하고, 재구성하십시오. 다음 코드는 입력으로 UTF-8 std::string를 받아 돌려 다른 UTF-8 std::string :

#include <unicode/utypes.h> 
#include <unicode/unistr.h> 
#include <unicode/translit.h> 

std::string desaxUTF8(const std::string& str) { 
    // UTF-8 std::string -> UTF-16 UnicodeString 
    UnicodeString source = UnicodeString::fromUTF8(StringPiece(str)); 

    // Transliterate UTF-16 UnicodeString 
    UErrorCode status = U_ZERO_ERROR; 
    Transliterator *accentsConverter = Transliterator::createInstance(
     "NFD; [:M:] Remove; NFC", UTRANS_FORWARD, status); 
    accentsConverter->transliterate(source); 
    // TODO: handle errors with status 

    // UTF-16 UnicodeString -> UTF-8 std::string 
    std::string result; 
    source.toUTF8String(result); 

    return result; 
} 
+0

매우 유용합니다. 나는 [: M :] 대신 [: Mn :]을 선호한다. 왜냐하면 후자는 힌디어 텍스트의 모음 표식을 제거하기 때문에 의미가 있다고 생각하기 때문이다. –

+0

@JyotirmoyBhattacharya 유니 코드가 만드는 distintion은 의미론이 아닌 레이아웃을 기반으로합니다. 이것은 힌디어에 대한 필요에 적합하지만 전체적으로 좋은 아이디어는 아닙니다. (발음 구별 부호는 여러 언어로 의미를 부여합니다.) 귀하의 의견에 감사드립니다! –