将字符串从UTF-8转换为ISO-8859-1

Chr*_*ord 7 c++ utf-8 iso-8859-1 iconv

我正在尝试将UTF-8 string转换为ISO-8859-1 char*以用于遗留代码.我看到这样做的唯一方法是iconv.

我肯定更喜欢完全string基于C++的解决方案,然后只需调用.c_str()生成的字符串.

我该怎么做呢?请尽可能使用代码示例.iconv如果它是你知道的唯一解决方案,我很好用.

Mar*_*som 11

将从另一个答案修改我的代码以实现Alf的建议.

std::string UTF8toISO8859_1(const char * in)
{
    std::string out;
    if (in == NULL)
        return out;

    unsigned int codepoint;
    while (*in != 0)
    {
        unsigned char ch = static_cast<unsigned char>(*in);
        if (ch <= 0x7f)
            codepoint = ch;
        else if (ch <= 0xbf)
            codepoint = (codepoint << 6) | (ch & 0x3f);
        else if (ch <= 0xdf)
            codepoint = ch & 0x1f;
        else if (ch <= 0xef)
            codepoint = ch & 0x0f;
        else
            codepoint = ch & 0x07;
        ++in;
        if (((*in & 0xc0) != 0x80) && (codepoint <= 0x10ffff))
        {
            if (codepoint <= 255)
            {
                out.append(1, static_cast<char>(codepoint));
            }
            else
            {
                // do whatever you want for out-of-bounds characters
            }
        }
    }
    return out;
}
Run Code Online (Sandbox Code Playgroud)

无效的UTF-8输入会导致字符丢失.


Che*_*Alf 6

首先将UTF-8转换为32位Unicode.

然后保留0到255范围内的值.

这些是Latin-1代码点,对于其他值,决定是将其视为错误还是替换为代码点127(我的收藏,ASCII"del")或问号等.


C++标准库定义了std::codecvt可以使用的特化,

template<>
codecvt<char32_t, char, mbstate_t>
Run Code Online (Sandbox Code Playgroud)

C++11§22.4.1.4/ 3:"专业化codecvt <char32_t, char, mbstate_t>在UTF-32和UTF-8编码方案之间进行转换"