C++ 将 UTF-8 字符串转换为 ICU 的 StringPiece
C++ Converting an UTF-8 string to ICU's StringPiece
第一次在这里发帖,所以如果我的标题/格式/标签不是应该的样子,请提前道歉。
我正试图在c++窗口控制台应用程序中创建一个函数,该函数将从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 "Ht„"
,而硬编码abcš
的值是正确的0x00b483d4 "abcš"
我做错了什么,最好的解决方法是什么?我已经尝试了这个线程中推荐的解决方案。
在过去的两天里,我一直在试图找到一个解决方案,但没有成功,所以任何帮助都将不胜感激。
提前谢谢。
后回答编辑:对于任何感兴趣的人来说,这是工作代码,非常感谢史蒂文·R·卢米斯的帮助;
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
iffstd::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
}
相关文章:
- 如何在 Linux for Windows 上通过 MinGW 构建静态 ICU 的 Boost
- 检测 ICU 库在 VS2017 中失败
- 如何调整ICU的UnicodeString::caseCompare(或获得相同的效果)
- 如何将ICU库添加到ARM的Qt项目中
- 在带有brew的MacOS上链接时缺少增强ICU正则表达式符号
- Ubuntu上的库ICU不想从Unicode转换为Windows-1251
- 默认区域设置"root"在 ICU 中如何工作?
- ICU 的未解析外部符号
- icu::SimpleDate格式使用未定义类型的编译器错误
- 如何在 c++ Linux 中使用 ICU 库将 UnicodeString 转换为 windows-1251
- 构建适用于 iOS 的 ICU
- Unicode - ICU 库 - 获取 UnicodeString 中的代码点计数
- C :如何使用ICU通过给定的时区偏移来获得当前时间
- C ICU库如何确定要缓存的日历对象
- ICU结合泰语元音符号和何时忽略
- 在将 cmake 项目与 Qt5 链接时部署 icu 库
- 如何与ICU 57.1 mingw静态链接我的应用程序
- UTF-8到UCS-2与icu库的转换
- 如何使用CMake部署ICU库
- C++ 将 UTF-8 字符串转换为 ICU 的 StringPiece