【问题标题】:how to use strtok to tokenize a expression using c++如何使用 strtok 使用 c++ 标记表达式
【发布时间】:2015-06-18 17:42:16
【问题描述】:

我需要使用 strok 标记一个数学表达式。我已经做了一些事情,但我无法为我的向量添加分隔符 当我运行我得到的代码时 2x 4y 6 3 这个输出 如何获得向量的分隔符以及如何获得这样的输出 2x + 4y ^ 6 - 3 我的代码

int main()
    {
    vector<string> finalVector;
        char input[1024]="2x+4y^6-3";
        char *token = strtok(input, "^+-/()/t");
        while (token != NULL) {
            finalVector.push_back(token);

                    token = strtok(NULL, "^+-/()/t");
                    }
        for (int i = 0; i < finalVector.size(); i++)
            cout << finalVector.at(i) << " ";
        return 0;
        }

【问题讨论】:

  • 您不能为此使用strtok,因为它会丢弃分隔符,而只会为您提供在分隔符之间的文本。没有办法让它不这样做。我会亲自使用手写标记器或flex标记器生成器来解决这个问题。
  • 您可能会使用编译器-编译器(Lex/Yacc、Bison、ANTLR、Boost ......),尽管它可能看起来有点矫枉过正。

标签: c++ strtok


【解决方案1】:

我知道您的问题是关于如何使用 strtok 执行此操作,但我的感觉是这最终会给您带来痛苦。我认为您至少应该考虑使用支持此功能的 boost tokenizer。事实上,boost 支持丢弃和保留分隔符的组合;保留的分隔符存储为它们自己的标记:

// char_sep_example_2.cpp
#include <iostream>
#include <boost/tokenizer.hpp>
#include <string>

int main()
{
  std::string str = ";;Hello|world||-foo--bar;yow;baz|";
  typedef boost::tokenizer<boost::char_separator<char> > 
      tokenizer;
  boost::char_separator<char> sep("-;", "|", boost::keep_empty_tokens);
  tokenizer tokens(str, sep);
  for (tokenizer::iterator tok_iter = tokens.begin();
      tok_iter != tokens.end(); ++tok_iter)
      std::cout << "<" << *tok_iter << "> ";

  std::cout << "\n";
  return 0;
}

The output is:
<> <> <Hello> <|> <world> <|> <> <|> <> <foo> <> <bar> <yow> <baz> <|> <>

这很容易做到你想要的。我的猜测是,这将为您节省大量时间。参考:http://www.boost.org/doc/libs/1_58_0/libs/tokenizer/char_separator.htm

【讨论】:

    【解决方案2】:

    strtok 将找到的分隔符替换为空字符。分隔符是不可恢复的消失了。

    如果您在第一次调用 strtok 之前复制了您的字符串,您可以恢复分隔符:

    char* to_strtok = strdup(input);
    const char* delims = "^+-/()/t";
    char* token;
    for (token = strtok(to_strtok, delims);
         token != 0;
         token = strtok(0, delims))
    {
      char delim = input[token - to_strtok + strlen(token)];
      if (delim != '\0')
      {
         printf ("token=\"%s\" delim='%c'\n", token, delim);
      }
      else
      {
         printf ("last token=\"%s\"n", token);
      }
    

    }

    【讨论】:

      猜你喜欢
      • 2021-08-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-02
      • 2015-05-12
      • 2012-05-04
      • 1970-01-01
      相关资源
      最近更新 更多