I’m trying to make a function to split a string, “Split At Spaces”, into a vector which would contain “Split” “At” “Spaces”. So far, this is the code I’ve got.
#include <iostream>
#include <utility>
#include <algorithm>
using namespace std;
std::vector<std::string> split(std::string * s, char * tosplit)
{
size_t i = 0;
int count = 0;
size_t contain;
std::vector<std::string> split;
std::cout << "Start" << std::endl;
std::cout << *s << std::endl;
std::cout << *tosplit << std::endl;
while((contain = s->find(*tosplit,i)) != std::string::npos)
{
count++;
i = contain + 1;
}
std::cout << "Contains " << count << std::endl;
if (count == 0)
{
std::cout << "Equals 0" << std::endl;
split = std::vector<std::string>(1);
split.at(0) = s->c_str();
return split;
}
split = std::vector<std::string>(count + 1);
split.begin();
int lasti;
i = s->find_first_of(*tosplit);
split.at(0) = s->substr(0, i);
lasti = i;
int runs = 1;
while (runs <= count)
{
i = s->find(*tosplit, lasti + 1);
std::cout << i << " " << lasti << std::endl;
split.at(runs) = s->substr(lasti, --i);
runs++;
lasti = i;
}
split.at(runs) = s->substr(lasti, s->size());
std::cout << "done, result is" << std::endl;
i = 0;
while (i < split.capacity())
{
std::cout << split.at(i) << std::endl;
i++;
}
return split;
}
It throws an out_of_range exception. Any help you can give would be appreciated. This is like my first part using pointers in a function so I’m kinda guessing here.
Thanks!
Please don’t suggest using x or y method, I’d like to write my own as I’m doing it for the experience.
Single Delimiter:
You wrote much too much code to do this. You can do it in a few lines. You are getting very over complicated. And there’s no reason to really do anything with pointers for this.
Multiple Delimiters:
A solution for using multiple delimiters is more complicated. You can no longer leverage off of
getline, which means you’re basically writing part ofgetline‘s functionality yourself. But still, it can be quite short.This will add blank strings when delimiters are next to each-other. If that’s not the desired behavior for adjacent delimiters, this can be easily avoided by guarding the
push_backwithif(start != end).Conclusion:
When you are starting to write a low level algorithm like this, pseudo code it out in broad terms and then before writing any code check what the C++ standard library can provide to cut out parts or all of your work. You’ll end up with smaller, less error prone, and more understandable code. No one wants to see a hand rolled implementation for
find_first_of, for example. It’s much more clear to read the wordsfind_first_of. It’s clear what that function is going to do, and that it’s bug free (hopefully).