A
Aaron Walker
I have a feeling this going to end up being something so stupid, but
right now I'm confused as hell.
I'm trying to code a function, that given a string and a delimiter char,
returns a vector of the sub-strings.
Here's what I have (I've thrown a main() in there for this mail).
---
#include <iostream>
#include <string>
#include <vector>
std::vector<std::string>
splitstr(const std::string &str, const char delim)
{
std::vector<std::string> vec;
std::string::size_type pos, lpos = 0;
while (true)
{
pos = str.find(delim, lpos);
if (pos == std::string::npos)
{
vec.push_back(str.substr(lpos));
break;
}
vec.push_back(str.substr(lpos, pos));
lpos = ++pos;
}
return vec;
}
int
main(int argc, char **argv)
{
if (argc != 2)
return 1;
std::vector<std::string> testvec = splitstr(argv[1], ' ');
std::cout << "testvec1 = [";
std::vector<std::string>::iterator i;
for (i = testvec.begin() ; i != testvec.end() ; ++i)
std::cout << "'" << *i << "', ";
std::cout << "]" << std::endl;
}
---
For some reason I cannot figure out, it's doing this:
$ ./splitstr "this is a test"
testvec1 = [ 'this', 'is a te', 'a test', 'test', ]
It looks like lpos is correct for every one, but pos is only correct for
the first and last elements.
When printing the value of pos and lpos on each iteration, it looks
correct. For example, the 2nd element in the vector above is lpos=5,
pos=7. How on earth can that equal a 7char string?
Anyone able to give me a kind shove in the right direction?
Thanks,
Aaron
right now I'm confused as hell.
I'm trying to code a function, that given a string and a delimiter char,
returns a vector of the sub-strings.
Here's what I have (I've thrown a main() in there for this mail).
---
#include <iostream>
#include <string>
#include <vector>
std::vector<std::string>
splitstr(const std::string &str, const char delim)
{
std::vector<std::string> vec;
std::string::size_type pos, lpos = 0;
while (true)
{
pos = str.find(delim, lpos);
if (pos == std::string::npos)
{
vec.push_back(str.substr(lpos));
break;
}
vec.push_back(str.substr(lpos, pos));
lpos = ++pos;
}
return vec;
}
int
main(int argc, char **argv)
{
if (argc != 2)
return 1;
std::vector<std::string> testvec = splitstr(argv[1], ' ');
std::cout << "testvec1 = [";
std::vector<std::string>::iterator i;
for (i = testvec.begin() ; i != testvec.end() ; ++i)
std::cout << "'" << *i << "', ";
std::cout << "]" << std::endl;
}
---
For some reason I cannot figure out, it's doing this:
$ ./splitstr "this is a test"
testvec1 = [ 'this', 'is a te', 'a test', 'test', ]
It looks like lpos is correct for every one, but pos is only correct for
the first and last elements.
When printing the value of pos and lpos on each iteration, it looks
correct. For example, the 2nd element in the vector above is lpos=5,
pos=7. How on earth can that equal a 7char string?
Anyone able to give me a kind shove in the right direction?
Thanks,
Aaron