【问题标题】:Is there an equivalent in C++ of PHP's explode() function? [duplicate]PHP 的explode() 函数在C++ 中是否有等价物? [复制]
【发布时间】:2012-10-09 15:18:09
【问题描述】:

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

在 PHP 中,explode() 函数将接受一个字符串并将其分割成一个数组,通过指定的分隔符分隔每个元素。

C++中有没有等价的函数?

【问题讨论】:

  • 不,但是编写自己的实现很容易。
  • boost::split 来自 [boost/algorithm/string.hpp](www.boost.org/doc/html/string_algo.html)
  • @KerrekSB 我认为你应该在关闭之前回答这个问题
  • 有一个题为“Splitting a string in C++”的问题。它有一些很好的解决方案。
  • 下面的答案和php的explode()有几个不同,here is a closer-to-php port

标签: php c++ arrays explode equivalent


【解决方案1】:

这是一个简单的示例实现:

#include <string>
#include <vector>
#include <sstream>
#include <utility>

std::vector<std::string> explode(std::string const & s, char delim)
{
    std::vector<std::string> result;
    std::istringstream iss(s);

    for (std::string token; std::getline(iss, token, delim); )
    {
        result.push_back(std::move(token));
    }

    return result;
}

用法:

auto v = explode("hello world foo bar", ' ');

注意:@Jerry 写入输出迭代器的想法对于 C++ 来说更为惯用。实际上,您可以同时提供两者;一个输出迭代器模板和一个产生向量的包装器,以获得最大的灵活性。

注意2:如果要跳过空标记,请添加if (!token.empty())。

【讨论】:

  • 在这种情况下 std::move 在做什么?有必要吗?我没有使用它进行编译,因为我没有使用 C++11,而且效果很好。但是这种情况的目的是什么?
  • @user1944429:此举避免了复制字符串数据。由于您在循环中不再使用它,因此向量直接“窃取”该数据而不复制它是有意义的。
  • 漏了一个case,在“a,b,c,d”的输入场景中,它应该返回5个值,包括最后一个null,但它没有
  • 如果需要我使用的,explode_cpp
  • @AlokSaini:没错,目前的代码有“可选的尾随分隔符”语义,而不是你想要的。解决此问题的最简单方法是添加检查 s.back() == delim 并在这种情况下发出另一个空字符串。
【解决方案2】:

标准库不包括直接等效的,但它是相当容易编写的。作为 C++,您通常不希望专门写入数组 - 相反,您通常希望将输出写入迭代器,因此它可以转到数组、向量、流等。这会给这个一般顺序的东西:

template <class OutIt>
void explode(std::string const &input, char sep, OutIt output) { 
    std::istringstream buffer(input);

    std::string temp;

    while (std::getline(buffer, temp, sep))
        *output++ = temp;
}

【讨论】:

  • 我认为std::getline 调用中存在错误。你在哪里有input 我相信应该是temp
  • @AntonioCS:糟糕,完全正确。谢谢!
猜你喜欢
  • 2019-11-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-14
  • 1970-01-01
  • 1970-01-01
  • 2018-03-26
  • 2012-06-08
相关资源
最近更新 更多