Hector Y. Martinez wrote:
Well, I have an char* and I need to separe it in pieces... for
example I have this:
"AREA_VERTEX -5.1108 -33.2878 0" and I need to separe this string in
an array of char* with this values...
[0] = "AREA_VERTEX"
[1] = "-5.1108"
[2] = "-33.287"
[3] = "0"
This values are separate by and blank space, please I need any good
Idea, I'm new working with strings in c++
If you're using std::string, here's a simple string splitter (and test
program). This approach is more efficient than using std::stringstream,
with different flexibility tradeoffs. One thing it won't do is skip
consequtive delimitters (e.g. two space) - if there are consequtive
delimitters, you'll get an empty string in the output list.
#include <string>
#include <vector>
#include <iostream>
using namespace std;
void split_string(
const string& str,
char delimitter,
vector<string>& ret
)
{
string::size_type delim;
string::size_type prev_delim = 0;
while (string::npos != (delim = str.find_first_of(delimitter,prev_delim)))
{
ret.push_back(str.substr(prev_delim,delim-prev_delim));
prev_delim = delim+1;
}
// Get the tail after the last separator
ret.push_back(str.substr(prev_delim));
}
int main(int argc, char* argv[])
{
if (3 > argc)
{
cerr << "usage: split_test pattern\n";
return 1;
}
vector<string> args;
split_string(argv[1],' ',args);
cout << args.size() << " arguments:\n";
for (vector<string>::iterator it = args.begin(); it != args.end(); ++it)
cout << "'" << *it << "'\n";
}