Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an equivalent in C++ of PHP's explode() function? [duplicate]

Tags:

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++?

like image 365
reformed Avatar asked Oct 19 '12 03:10

reformed


People also ask

What is the difference between explode () and split () functions?

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.

What does the explode () function return?

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.

What does the explode () function do?

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.

What is the purpose of the explode () and implode () functions in PHP?

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.


1 Answers

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()).

like image 163
Kerrek SB Avatar answered Sep 25 '22 15:09

Kerrek SB