按指定分隔符拆分wstring字符串

5
我有一个包含文本的std::wstring变量,我需要通过分隔符将其拆分。我该怎么做?我不想使用会产生警告的boost库。谢谢。 编辑1 这是一个示例文本:

嗨,你好吗?

这是代码:
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;
}

结果如下:

  1. 怎么样
  2. 你好吗

我不明白为什么最后一个字符总是被分割成另一个标记...


1
可能是如何在C++中对字符串进行分词?的重复问题,许多方法都包括使用和不使用boost。 - Ben Voigt
4个回答

7

在你的代码中,问号出现在单独的一行上,因为这是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';
        }

}

test run: https://ideone.com/jOeH9


2
您正在进行默认构造boost::char_separator。根据文档,该函数使用std::isspace()来识别已删除的分隔符,使用std::ispunct()来识别保留的分隔符。此外,空令牌将被删除。由于std::ispunct(L'?')为true,因此它被视为“保留”的分隔符,并作为单独的标记报告。

1

你说你不想用boost,那么...

这可能是在C++中使用的一种奇怪的方法,但我曾经在一个需要大量C语言标记化的MUD中使用过它。

拿这个分配给char * chars的内存块:

char chars[] = "I like to fiddle with memory";

如果你需要在空格字符上进行标记化:

create array of char* called splitvalues big enough to store all tokens
while not increment pointer chars and compare value to '\0'
  if not already set set address of splitvalues[counter] to current memory address - 1
     if value is ' ' write 0 there
       increment counter

当你完成后,原始字符串将被销毁,因此不要使用它,而是使用指向令牌的字符串数组。令牌的计数是计数器变量(数组的上限)。

方法如下:

  • 迭代字符串,并在第一次出现时更新令牌起始指针
  • 将您需要拆分的字符转换为C中表示字符串终止的零
  • 计算您执行此操作的次数

附:不确定是否可以在Unicode环境中使用类似的方法。


1

你好,你可以使用wcstok函数。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接