Possible Duplicate:
Splitting a string in C++
In PHP, the explode()
function will take a string and chop it up into an array separating each element by a specified delimiter.
Is there an equivalent function in C++?
Both are used to split a string into an array, but the difference is that split() uses pattern for splitting whereas explode() uses string. explode() is faster than split() because it doesn't match string based on regular expression.
explode() is a built in function in PHP used to split a string in different strings. The explode() function splits a string based on a string delimiter, i.e. it splits the string wherever the delimiter character occurs. This functions returns an array containing the strings formed by splitting the original string.
The explode function is utilized to "Split a string into pieces of elements to form an array". The explode function in PHP enables us to break a string into smaller content with a break. This break is known as the delimiter.
PHP Explode function breaks a string into an array. PHP Implode function returns a string from an array. PHP implode and PHP explode are two common functions used in PHP when working with arrays and strings in PHP.
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; }
Usage:
auto v = explode("hello world foo bar", ' ');
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.
Note 2: If you want to skip empty tokens, add if (!token.empty())
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With