[英]C++ Converting an UTF-8 string to ICU's StringPiece
第一次在这里发布,因此如果我的标题/格式/标签不应该如此,请提前道歉。
我正在尝试在c ++ Windows控制台应用程序中创建一个函数,该函数将从std::wstring
用户输入中删除变音符号。 为此,我使用的是在此问题的帮助下创建的代码,并将我的wstring转换为UTF-8字符串,如下所示:
std::string test= wstring_to_utf8 (input);
std::string wstring_to_utf8 (const std::wstring& str){
std::wstring_convert<std::codecvt_utf8<wchar_t>> myconv;
return myconv.to_bytes(str);
}
std::string output= desaxUTF8(test);
与desaxUTF8(...)是:
#include <unicode/utypes.h>
#include <unicode/unistr.h>
#include <unicode/ustream.h>
#include <unicode/translit.h>
#include <unicode/stringpiece.h>
std::string desaxUTF8(const std::string& str) {
StringPiece s(str);
UnicodeString source = UnicodeString::fromUTF8(s);
//...
return result;
}
这是我遇到问题的地方。 StringPiece s
不能正确地从string str
接收值,而是被设置为不正确的值。
但是如果我要替换StringPiece s(str);
具有硬编码的值,例如StringPiece s("abcš");
,效果很好。
使用VS2015调试器时,用户输入abcš
StringPiece s
上的值是错误的0x0028cdc0 "H\\t„"
,而硬编码abcš
的值是正确的0x00b483d4 "abcš"
我做错了什么,解决此问题的最佳方法是什么? 我已经从该线程尝试了推荐的解决方案。
我花了最后两天的时间来寻找无济于事的解决方案,因此对您的帮助将不胜感激。
先感谢您。
发布答案编辑:对于任何感兴趣的人,这里都是有效的代码,在此感谢Steven R. Loomis的实现;
std::wstring Menu::removeDiacritis(const std::wstring &input) {
UnicodeString source(FALSE, input.data(), input.length());
UErrorCode status = U_ZERO_ERROR;
Transliterator *accentsConverter = Transliterator::createInstance(
"NFD; [:M:] Remove; NFC", UTRANS_FORWARD, status);
accentsConverter->transliterate(source);
std::wstring output(source.getBuffer(), source.length());
return output;
}
@NuSkooler(嗨!)当然是现场。 无论如何,请尝试在UnicodeString
和std::wstring
之间进行转换, 如果 std::wstring
实际上是UTF-16。 (未测试)
std::wstring doSomething(const std::wstring &input) {
#if(sizeof(wchar_t) != sizeof(UChar))
#error no idea what (typically underspecified) wchar_t actually is.
#else
// source is a read-only alias to the input data
const UnicodeString source(FALSE, input.data(), input.length());
// DO SOMETHING with the data
UnicodeString target = SOME_ACTUAL_FUNCTION(source); // <<<< Put your actual code here
// construct an output wstring
std::wstring output(target.getBuffer(), target.length());
// return it
return output;
#endif
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.