【问题标题】:Split Function c++ [duplicate]拆分函数c ++ [重复]
【发布时间】:2012-09-16 10:27:09
【问题描述】:

可能重复:
Splitting a string in C++

我需要一个拆分功能。

必须像这样工作:

buffer = split(str, ' ');

我搜索了一个拆分函数,尝试了 boost 库,但一切都不好:/

【问题讨论】:

标签: c++ split


【解决方案1】:
标准 c 库中的

strtok() 非常好,可以满足您的需求。除非你热衷于从多个线程中使用它并且担心函数不能重入,我不怀疑这里是这种情况。

附:以上假设您有一个字符数组作为输入。如果它是一个 c++ 字符串,你仍然可以在使用 strtok 之前使用 string.c_str 来获取 c 字符串

【讨论】:

    【解决方案2】:

    boost lib 应该也可以工作。

    像这样使用它:

    vector <string> buffer;
    boost::split(buffer, str_to_split, boost::is_any_of(" "));
    

    已添加
    确保包含算法:

    #include <boost/algorithm/string.hpp>
    

    像这样打印到 std::cout:

    vector<string>::size_type sz = buffer.size();
    cout << "buffer contains:";
    for (unsigned i=0; i<sz; i++)
    cout << ' ' << buffer[i];
    cout << '\n';
    

    【讨论】:

      【解决方案3】:

      我猜strtok() 就是你要找的东西。

      它允许您始终返回由给定字符分隔的第一个子字符串:

      char *string = "Hello World!";
      char *part = strtok(string, " "); // passing a string starts a new iteration
      while (part) {
          // do something with part
          part = strtok(NULL, " "); // passing NULL continues with the last string
      }
      

      请注意,此版本不得同时在多个线程中使用(还有一个版本(strtok_s()more details here),它有一个附加参数,可以使其在并行化环境中工作)。对于您希望在循环中拆分子字符串的情况也是如此。

      【讨论】:

        猜你喜欢
        • 2023-03-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-09-05
        • 2015-01-09
        • 2021-07-28
        • 1970-01-01
        • 2023-03-24
        相关资源
        最近更新 更多