简介
分割使用一个给定的分隔符的字符串是一个非常常见的操作。
不幸的是,STL没有提供任何直接的方式实现这一目标。
这种分裂实施templatised和使用类型推演,以确定什么样的字符串和容器作为参数,这必须是某种形式的basic_stringlt; GT;和任何容器实现push_back()方法被传递。
可直接进入的文件,它是用来放置代码,或创建一个单独的包括文件。
注意,未完全指定的字符串类型,允许的特点和分配器为默认。
在某些情况下,这可能不是你想要的,有些编译器可能不喜欢它。背景
我写这篇时,我发现,公司的Paul J. Weiss编写的代码与标题比我为这个共同的简单的情况下需要更复杂的。
最常见的情况应该是最容易写的。源代码
用法示例{C}
template <typename E, typename C>
size_t split(std::basic_string<E> const& s,
C &container,
E const delimiter,
bool keepBlankFields = true)
{
size_t n = 0;
std::basic_string<E>::const_iterator it = s.begin(), end = s.end(), first;
for (first = it; it != end; ++it)
{
// Examine each character and if it matches the delimiter
if (delimiter == *it)
{
if (keepBlankFields || first != it)
{
// extract the current field from the string and
// append the current field to the given container
container.push_back(std::basic_string<E>(first, it));
++n;
// skip the delimiter
first = it + 1;
}
else
{
++first;
}
}
}
if (keepBlankFields || first != it)
{
// extract the last field from the string and
// append the last field to the given container
container.push_back(std::basic_string<E>(first, it));
++n;
}
return n;
}