我有这段代码,它将 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/