对于那个些需要使用字符串分隔符拆分字符串的人,也许可以尝试我的以下解决方案。
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
.
我认为这不是最有效的代码,但至少它可以工作。希望有帮助。