我有一个包含文本的 std::wstring 变量,我需要用分隔符将它拆分。我怎么能这样做?我不会使用会产生一些警告的 boost。谢谢
编辑 1 这是一个示例文本:
hi how are you?
这是代码:
typedef boost::tokenizer<boost::char_separator<wchar_t>, std::wstring::const_iterator, std::wstring> Tok;
boost::char_separator<wchar_t> sep;
Tok tok(this->m_inputText, sep);
for(Tok::iterator tok_iter = tok.begin(); tok_iter != tok.end(); ++tok_iter)
{
cout << *tok_iter;
}
结果是:
- 嗨
- 如何
- 是
- 你
- ?
我不明白为什么最后一个字符总是拆分成另一个标记...
最佳答案
在您的代码中,问号出现在单独的一行中,因为这是默认情况下 boost::tokenizer 的工作方式。
如果您想要的输出是四个标记(“hi”、“how”、“are”和“you?”),您可以
a) 将您使用的 char_separator 更改为
boost::char_separator<wchar_t> sep(L" ", L"");
b) 使用 boost::split
,我认为这是对“按指定字符拆分 wstring”的最直接回答
#include <string>
#include <iostream>
#include <vector>
#include <boost/algorithm/string.hpp>
int main()
{
std::wstring m_inputText = L"hi how are you?";
std::vector<std::wstring> tok;
split(tok, m_inputText, boost::is_any_of(L" "));
for(std::vector<std::wstring>::iterator tok_iter = tok.begin();
tok_iter != tok.end(); ++tok_iter)
{
std::wcout << *tok_iter << '\n';
}
}
关于c++ - 按指定的分隔符拆分 wstring,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5425092/