Для тех, кому нужна альтернатива в разбиении строки с разделителем строк, возможно, вы можете попробовать мое следующее решение.
std::vector<size_t> str_pos(const std::string &search, const std::string &target)
{
std::vector<size_t> founds;
if(!search.empty())
{
size_t start_pos = 0;
while (true)
{
size_t found_pos = target.find(search, start_pos);
if(found_pos != std::string::npos)
{
size_t found = found_pos;
founds.push_back(found);
start_pos = (found_pos + 1);
}
else
{
break;
}
}
}
return founds;
}
std::string str_sub_index(size_t begin_index, size_t end_index, const std::string &target)
{
std::string sub;
size_t size = target.length();
const char* copy = target.c_str();
for(size_t i = begin_index; i <= end_index; i++)
{
if(i >= size)
{
break;
}
else
{
char c = copy[i];
sub += c;
}
}
return sub;
}
std::vector<std::string> str_split(const std::string &delimiter, const std::string &target)
{
std::vector<std::string> splits;
if(!delimiter.empty())
{
std::vector<size_t> founds = str_pos(delimiter, target);
size_t founds_size = founds.size();
if(founds_size > 0)
{
size_t search_len = delimiter.length();
size_t begin_index = 0;
for(int i = 0; i <= founds_size; i++)
{
std::string sub;
if(i != founds_size)
{
size_t pos = founds.at(i);
sub = str_sub_index(begin_index, pos - 1, target);
begin_index = (pos + search_len);
}
else
{
sub = str_sub_index(begin_index, (target.length() - 1), target);
}
splits.push_back(sub);
}
}
}
return splits;
}
Эти фрагменты состоят из 3 функций. Плохая новость заключается в том, что для использования функции str_split
вам понадобятся две другие функции. Да, это огромный кусок кода. Но хорошая новость заключается в том, что эти две дополнительные функции могут работать независимо друг от друга, а иногда и могут быть полезны ...
Протестировал функцию в main()
блоке так:
int main()
{
std::string s = "Hello, world! We need to make the world a better place. Because your world is also my world, and our children's world.";
std::vector<std::string> split = str_split("world", s);
for(int i = 0; i < split.size(); i++)
{
std::cout << split[i] << std::endl;
}
}
И это даст:
Hello,
! We need to make the
a better place. Because your
is also my
, and our children's
.
Я считаю, что это не самый эффективный код, но, по крайней мере, он работает. Надеюсь, это поможет.