2012-10-19 54 views
14

可能重复:
Splitting a string in C++在PHP的explode()函数的C++中是否有等价物?

在PHP中,explode()功能将一个字符串,并把它切碎了到一个数组由指定的分隔符分隔每个元件。

在C++中是否有等价函数?

+1

不,但它很容易编写自己的实现。 –

+1

'boost :: split' from [boost/algorithm/string.hpp](www.boost.org/doc/html/string_algo.html) – Praetorian

+0

@KerrekSB我想你应该在这个关闭之前做出答案 –

回答

28

这里有一个简单的例子实现:

#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", ' '); 

注:@写入输出迭代器的杰里的想法是对C更地道++。事实上,你可以同时提供;一个输出迭代器模板和一个产生矢量的包装器,以实现最大的灵活性。

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

+0

在这种情况下做什么std :: move?有必要吗?我编译没有它,因为我没有使用C++ 11,它没有问题。但是这种情况下的目的是什么? –

+4

@ user1944429:此举避免了复制字符串数据。由于在循环中没有更多的用途,因此矢量直接“窃取”数据而不复制它是有意义的。 –

+0

它错过了一个案例,在“a,b,c,d”的输入场景中, 它应该返回包括最后一个null在内的5个值,但如果需要的话,它不需要 –

11

标准库不包括直接等价物,但是这是一个相当容易写的东西。作为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, input, sep)) 
     *output++ = temp; 
} 
相关问题