【问题标题】:Split a wstring by specified separator通过指定的分隔符拆分 wstring
【发布时间】:2011-07-22 10:59:37
【问题描述】:

我有一个包含文本的 std::wstring 变量,我需要用分隔符将其拆分。我怎么能这样做?我不会使用产生一些警告的提升。谢谢

编辑 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. 如何
  3. ?

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

【问题讨论】:

标签: c++ string split


【解决方案1】:

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

}

试运行:https://ideone.com/jOeH9

【讨论】:

    【解决方案2】:

    你默认构造boost::char_separatorThe documentation 说:

    函数 std::isspace() 用于识别已删除的分隔符,而 std::ispunct() 用于识别保留的分隔符。此外,还会丢弃空令牌。

    由于std::ispunct(L'?') 为真,它被视为“保留”分隔符,并报告为单独的标记。

    【讨论】:

      【解决方案3】:

      你说你不想提升所以......

      这可能是在 C++ 中使用的一种奇怪的方法,但我在 MUD 中使用了它,我需要在 C 中进行大量标记化。

      把这块内存分配给char * chars:

      char chars[] = "我喜欢摆弄记忆";

      如果您需要对空格字符进行标记:

      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 环境中使用类似的方法。

      【讨论】:

        【解决方案4】:

        您好,您可以使用wcstok 功能

        【讨论】:

          猜你喜欢
          • 2021-06-14
          • 1970-01-01
          • 2019-05-11
          • 1970-01-01
          • 2014-03-02
          • 1970-01-01
          • 1970-01-01
          • 2013-10-30
          • 1970-01-01
          相关资源
          最近更新 更多