c++ - 如何在 C++ Linux 中使用 ICU 库将 UnicodeString 转换为 windows-1251?

标签 c++ unicode icu unicode-string

我有这段代码,它将 UTF-8 字符串转换为 Unicode:

#include <unicode/unistr.h>
//included other header files

int main(int argc, char** argv) {
    std::string s("some string");
        // convert std::string to ICU's UnicodeString
        UnicodeString ucs = UnicodeString::fromUTF8(StringPiece(s.c_str()));

        // convert UnicodeString to std::wstring
        std::wstring ws;
        for (int i = 0; i < ucs.length(); ++i)
            ws += static_cast<wchar_t>(ucs[i]);

        std::wcout << ws;
}

我不明白如何将此 UnicodeString 转换为 windows-1251 (cp1251)。我应该在 Linux 中使用哪个函数来执行此操作?

最佳答案

ucnv.h 中使用 ICU 的转换函数(参见 ICU 文档中的 Conversion > Using Converters):

#include <memory>
#include <unicode/ucnv.h>
bool convertTo1251(std::vector<UChar> const & input, std::vector<char> & output)
{
    UErrorCode status = U_ZERO_ERROR;
    UConverter *pConvert = ucnv_open("windows-1251", &status);
    if (status)
    {
        printf("Failed to obtain char set converter: %d\r\n", status);
        return false;
    }
    std::shared_ptr<UConverter> cnv(pConvert, ucnv_close);

    UChar const * pwszBegin = &input[0], *pwszEnd = pwszBegin + input.size();
    output.resize(input.size());

    char *pszBegin = &output[0], *pszEnd = pszBegin + input.size();

    ucnv_fromUnicode(pConvert, &pszBegin, pszEnd, &pwszBegin, pwszEnd, nullptr, true, &status);
    if (status)
    {
        // deal with error
        return false;
    }
    return true;
}

关于c++ - 如何在 C++ Linux 中使用 ICU 库将 UnicodeString 转换为 windows-1251?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48154898/

相关文章:

c++ - 管理 C++ 委托(delegate)生命周期

c# - 为什么用于 Unicode 属性测试的 C# System.Char 方法有两个重载?

python - 如何使用python将阿拉伯字符映射到英文字符串

PHP 函数 imagettftext() 和 unicode

c++ - ICU ustdio.h 函数 : Undefined symbols on Mac OS when building with CMake

c++ - 使用 gcc 编译的应用程序与使用不同 gcc 版本编译的库不同

android - 找不到 opencv.hpp?安卓NDK

c++ - 递归传递动态变量的内存泄漏

java - CharsetICU 字符集转换的 java 示例

ios - 为什么我的模式在非用户换行符处停止?