簡體   English   中英

C++:如何將 ASCII 或 ANSI 轉換為 UTF8 並存儲在 std::string 中

[英]C++: how to convert ASCII or ANSI to UTF8 and stores in std::string

我的公司使用一些這樣的代碼:

    std::string(CT2CA(some_CString)).c_str()

我相信它將 Unicode 字符串(其類型為 CString)轉換為 ANSI 編碼,並且該字符串用於電子郵件的主題。 但是,電子郵件的標題(包括主題)表明郵件客戶端應該將其解碼為 un​​icode(原始代碼就是這樣做的)。 因此,某些德語字符(如“ä ö ü”)將無法正確顯示為標題。

無論如何,我可以將此標頭放回 UTF8 並存儲到 std::string 或 const char* 中嗎?

我知道有很多更聰明的方法可以做到這一點,但我需要保持代碼堅持其原始方法(即,將標頭作為 std::string 或 const char* 發送)。

提前致謝。

小心:它是'|' 而不是 '&' !

*buffer++ = 0xC0 | (c >> 6);
*buffer++ = 0x80 | (c & 0x3F);

這聽起來像是從一種編碼到另一種編碼的簡單轉換:您可以std::codecvt<char, char, mbstate_t>使用std::codecvt<char, char, mbstate_t> 但是,我不知道您的實現是否帶有合適的轉換。 從它的聲音來看,您只是嘗試將ISO-Latin-1轉換為 Unicode。 這應該非常簡單:前 128 個字符(0 到 127)映射到 UTF-8,后半部分可以方便地映射到相應的 Unicode 代碼點,即,您只需要將相應的值編碼為 UTF-8。 每個字符將被替換為兩個字符。 那它,我認為轉換是這樣的:

// Takes the next position and the end of a buffer as first two arguments and the
// character to convert from ISO-Latin-1 as third argument.
// Returns a pointer to end of the produced sequence.
char* iso_latin_1_to_utf8(char* buffer, char* end, unsigned char c) {
    if (c < 128) {
        if (buffer == end) { throw std::runtime_error("out of space"); }
        *buffer++ = c;
    }
    else {
        if (end - buffer < 2) { throw std::runtime_error("out of space"); }
        *buffer++ = 0xC0 | (c >> 6);
        *buffer++ = 0x80 | (c & 0x3f);
    }
    return buffer;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM