有没有PHP的爆炸()函数在C ++中等价? [英] Is there an equivalent in C++ of PHP's explode() function?
本文介绍了有没有PHP的爆炸()函数在C ++中等价?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可能重复:结果
拆分在C ++字符串
在PHP中,爆炸()
函数将一个字符串,砍它到一个数组由指定的分隔符的每个元素。
In PHP, the explode()
function will take a string and chop it up into an array separating each element by a specified delimiter.
有没有用C同等职能++?
Is there an equivalent function in C++?
推荐答案
下面是一个简单的例子实现:
Here's a simple example implementation:
#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更地道++。事实上,你可以同时提供;输出迭代器模板,并产生一个载体,实现最大的灵活性的包装。
Note: @Jerry's idea of writing to an output iterator is more idiomatic for C++. In fact, you can provide both; an output-iterator template and a wrapper that produces a vector, for maximum flexibility.
注2:(!token.empty())。如果你想跳过空标记,添加如果
Note 2: If you want to skip empty tokens, add if (!token.empty())
.
这篇关于有没有PHP的爆炸()函数在C ++中等价?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文