将utf8编码的字符串转换为本地8位编码的字符串,并将无法确定的字符替换为空白



我需要将utf-8字符串转换为本地8位编码字符串(单个字符用char表示),并保持结果字符串中的字符数不变。因此,我希望原始utf字符串中不确定的字符成为结果字符串中的空白。不幸的是,boost::locale::conv::from_utf没有提供这样的转换方法。它只提供两个:

enum    boost::locale::conv::method_type { boost::locale::conv::skip = 0, boost::locale::conv::stop = 1, boost::locale::conv::default_method = skip }

这意味着您可以跳过一个不确定的字符(然后结果字符串会更短)或引发异常。

我找到了使用boost使转换按我想要的方式工作的唯一方法——对字符串进行迭代,将每个字符转换为本地8位编码,在这个过程中捕捉异常,并手动插入空白。然而,这种方法并不有效,并且导致甚至更多的编码转换。这是代码:

std::string from_utf8_to_local(
const std::string& str,
const std::locale& loc)
{
std::u32string utext = boost::locale::conv::utf_to_utf<char32_t>(str);
std::string textLocal;
for(char32_t ch : utext)
{
std::string newChar;
try
{
std::u32string convStr;
convStr += ch;
std::string utf8Str =
boost::locale::conv::utf_to_utf<char>(convStr);
newChar = boost::locale::conv::from_utf(
utf8Str,
loc,
boost::locale::conv::stop);
}
catch(boost::locale::conv::conversion_error& /*error*/)
{
newChar = " ";
}
textLocal.append(newChar);
}
return textLocal;
}

问题是:

有没有办法用boost或stl以正确的方式做到这一点?

如果没有,我如何使用其他库?

如果您在Windows上,您可以使用MultiByteToWideChar从UTF-8转换为宽字符串(UTF-16)。然后,您可以使用WideCharToMultiByte从宽字符转换为您想要的任何编码(请参阅此列表)。要为不确定的字符获取空格,您需要使用第七个参数(lpDefaultChar)。

最新更新