我正在尝试创建一个函数将字符串“Split At Spaces”拆分为一个包含“Split”“At”“Spaces”的向量。到目前为止,这是我得到的代码。
#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;
}
它抛出一个 out_of_range 异常。您可以提供的任何帮助将不胜感激。这就像我在函数中使用指针的第一部分,所以我在这里有点猜测。
谢谢!
请不要建议使用 x 或 y 方法,我想写我自己的,因为我这样做是为了体验。