c++ - UTF8 数据到 std::string 或 std::wstring

标签 c++ string encoding std wstring

我从 HTTP 服务器响应中收到正文字节,但我不知道如何将它们转换为 UTF8 字符串以使用它们。

我有一个想法,但我不确定它是否可行。我需要获取响应的字节并搜索它们并修改它们,所以我需要转换 std::vector<BYTE>std::wstringstd::string .

响应的 UTF8 字节编码在我的 std::vector<BYTE> 中,如何将它们转换为 std::string ?我可以将它们转换为 std::wstring 吗? ?

我找到了这段代码:

std::string Encoding::StringToUtf8(const std::string& str)
{
INT size = MultiByteToWideChar(CP_ACP, MB_COMPOSITE, str.c_str(), str.length(), NULL, 0);

std::wstring utf16_str(size, '\0');

MultiByteToWideChar(CP_ACP, MB_COMPOSITE, str.c_str(), str.length(), &utf16_str[0], size);

INT utf8_size = WideCharToMultiByte(CP_UTF8, 0, utf16_str.c_str(), utf16_str.length(), NULL, 0, NULL, NULL);

std::string utf8_str(utf8_size, '\0');

WideCharToMultiByte(CP_UTF8, 0, utf16_str.c_str(), utf16_str.length(), &utf8_str[0], utf8_size, NULL, NULL);

return utf8_str;

但是现在如果我想在字符串中搜索像“Ñ”这样的字符会起作用吗?或者我是否需要转换 std::wstring 中的字节?并搜索“Ñ”修改std::wstring并将其转换为 std::string

这两个哪个是正确的?

我需要将 UTF8 响应放在 std::string 中或 std::wstring以便搜索和修改数据(带有特殊字符)并以 UTF8 格式重新发送响应给客户端。

最佳答案

std::string 中存储 utf-8只不过是将字节序列存储在“vector ”中。 std::string不知道任何编码内容,以及任何成员函数,如 find<algorithm>功能类似于std::find一旦您需要在标准 ASCII 之外工作,它将无法工作。所以这取决于你如何处理这种情况,你可以尝试将你的输入( L"Ñ" )转换为 utf-8 序列并尝试在 std::string 中找到它或者你可以转换你的 stringwstring并直接在上面工作。恕我直言,在您必须操作(搜索、提取单词、按字母拆分或替换,以及所有超出 ASCII 范围的所有这些)的情况下,您最好坚持输入 wstring并在将其发布到客户端之前转换为 utf-8 std::string
EDIT001:截至std::codecvt_utf8上面的评论和我对性能问题的评论中提到的。这是测试

std::wstring foo(const std::string& input)
{
    std::wstring_convert<std::codecvt_utf8<wchar_t>> converter;
    return converter.from_bytes(input.c_str());
}

std::wstring baz(const std::string& input)
{
    std::wstring retVal;
    auto targetSize = MultiByteToWideChar(CP_UTF8, 0, input.c_str(), static_cast<int>(input.size()), NULL, 0);
    retVal.resize(targetSize);
    auto res = MultiByteToWideChar(CP_UTF8, 0, input.c_str(), static_cast<int>(input.size()),
                                   const_cast<LPWSTR>(retVal.data()), targetSize);
    if(res == 0)
    {
        // handle error, throw, do something...
    }
    return retVal;
}

int main()
{
    std::string input = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut "
                        "labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco "
                        "laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in "
                        "voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat "
                        "cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.";

    {
        auto start = std::chrono::high_resolution_clock::now();
        for(int i = 0; i < 100'000; ++i)
        {
            auto result = foo(input);
        }
        auto end = std::chrono::high_resolution_clock::now();
        auto res = std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count();
        std::cout << "Elapsed time: " << res << std::endl;
    }

    {
        auto start = std::chrono::high_resolution_clock::now();
        for(int i = 0; i < 100'000; ++i)
        {
            auto result = baz(input);
        }
        auto end = std::chrono::high_resolution_clock::now();
        auto res = std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count();
        std::cout << "Elapsed time: " << res << std::endl;
    }
    return 0;
}

作为 Release x64 编译和运行时的结果
耗时:3065 耗时:29

两个数量级...

关于c++ - UTF8 数据到 std::string 或 std::wstring,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43068506/

相关文章:

ubuntu 中的 C++(linux 平台)

c++ - Apple Mach O-Linker 错误 Xcode (C++) : Undefined symbols for architecture x86_64

c++ - 为什么在这里使用进程替换会导致挂起?

java - Sqlite + Android 行结果中的空列

PHP 转义 shell arg 不需要的行为

c++ - 浮点,相等比较是否足以防止被零除?

python - python中unicode字符串的转换

python - 为什么不能将字节字符串用作 Docstrings?

javascript - 我如何检查对象的 typeSoftware 是否具有 (-1) 值并将其从中删除?

java或eclipse utf8编码不正确