gpt4 book ai didi

c++ - 如何搜索从 wstringstream 获得的宽字符串中的文本

转载 作者:行者123 更新时间:2023-11-28 06:11:35 32 4
gpt4 key购买 nike

我有一个单词流,在循环的每次运行中给我一个单词作为 std::string。但理想情况下,这应该是 std::wstring。因此,在获得字符串后,我将其转换为 std::wstring。这是我输入到 std:wstringstream 中的。最后,在处理完流中的所有单词后,我将 std:wstringstream 转换为 std::wstring,然后搜索所需的术语(最初是std::wstring) 在其中。这是我的代码:

while (stream)
{
std::string word = stream->getWord();
boost::trim(word);

std::wstring longWord(word.length(), L' '); // Make room for characters
std::copy(word.begin(), word.end(), longWord.begin());

fMyWideCharStream << longWord;
stream->next();
}

std::wstring fContentString = fMyWideCharStream.str();

size_t nPos = fContentString.find(fSearchString, 0); //fSearchString is std::wstring

while(nPos != std::wstring::npos)
{
qDebug() << "Pos: " << nPos << endl;
nPos = fContentString.find(fSearchString, nPos+1);
}

我有这个字符串:Passive Aggressive Dealing With Passive Aggression, Lost Happiness & Disconnection 版权所有 © 2014,其中 © 是一个宽字符。作为 std::string 它占据了两个位置。作为 std::wstring 它需要 1,这正是我想要的。但是,在尝试使用值为 L"2014"fSearchString 时,我得到的值仍然是 96,而它应该是 95,因为这个字符串现在是 std::wstring.

知道我应该怎么做才能解决这个问题吗?

最佳答案

因为原始的 string 不是纯 ASCII - 它包含多字节字符 '©',所以从 string 转换为 wstring 是错误的> 使用逐字符转换。因此两者

std::wstring longWord(word.length(), L' '); // Make room for characters
std::copy(word.begin(), word.end(), longWord.begin());

std::wstring longWord(word.begin(), word.end());

不适用于包含多字节字符的 string。要在 Windows 上将多字节字符 string 正确转换为 wstring,您可以使用 mbstowcs(): http://www.cplusplus.com/reference/cstdlib/mbstowcs/

以独立于平台的方式,使用 C++11(将选项编译为 clang:-std=c++1),您可以这样做:https://stackoverflow.com/a/14809553/1915854 , https://stackoverflow.com/a/18597384/1915854

如果您需要超出单个 wchar_t 可以存储的字符的示例:

std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;
std::wstring longWord = converter.from_bytes(word);

如果您不需要超出单个 wchar_t 可以存储的字符:

std::wstring_convert<std::codecvt_utf8<wchar_t>> converter;
std::wstring longWord = converter.from_bytes(word);

必要的包括:

#include <locale>
#include <codecvt>
#include <string>

在 Boost 中,C++11 之前似乎还有其他选项。

关于c++ - 如何搜索从 wstringstream 获得的宽字符串中的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31169355/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com