C++ 将 UTF-8 字符串转换为 ICU 的 StringPiece

C++ Converting an UTF-8 string to ICU's StringPiece

本文关键字:ICU StringPiece 转换 UTF-8 字符串 C++      更新时间:2023-10-16

第一次在这里发帖,所以如果我的标题/格式/标签不是应该的样子,请提前道歉。

我正试图在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(嗨!)当然很到位。在任何情况下,尝试在UnicodeStringstd::wstringiffstd::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
}