我知道很晚才来参加聚会,但我正在考虑最优雅的方法,如果给你一系列分隔符而不是空格,并且只使用标准库。
以下是我的想法:
要通过分隔符序列将单词拆分为字符串向量,请执行以下操作:
template<class Container>
std::vector<std::string> split_by_delimiters(const std::string& input, const Container& delimiters)
{
std::vector<std::string> result;
for (auto current = begin(input) ; current != end(input) ; )
{
auto first = find_if(current, end(input), not_in(delimiters));
if (first == end(input)) break;
auto last = find_if(first, end(input), is_in(delimiters));
result.emplace_back(first, last);
current = last;
}
return result;
}
通过提供一系列有效字符,以另一种方式进行拆分:
template<class Container>
std::vector<std::string> split_by_valid_chars(const std::string& input, const Container& valid_chars)
{
std::vector<std::string> result;
for (auto current = begin(input) ; current != end(input) ; )
{
auto first = find_if(current, end(input), is_in(valid_chars));
if (first == end(input)) break;
auto last = find_if(first, end(input), not_in(valid_chars));
result.emplace_back(first, last);
current = last;
}
return result;
}
is_in和not_in的定义如下:
namespace detail {
template<class Container>
struct is_in {
is_in(const Container& charset)
: _charset(charset)
{}
bool operator()(char c) const
{
return find(begin(_charset), end(_charset), c) != end(_charset);
}
const Container& _charset;
};
template<class Container>
struct not_in {
not_in(const Container& charset)
: _charset(charset)
{}
bool operator()(char c) const
{
return find(begin(_charset), end(_charset), c) == end(_charset);
}
const Container& _charset;
};
}
template<class Container>
detail::not_in<Container> not_in(const Container& c)
{
return detail::not_in<Container>(c);
}
template<class Container>
detail::is_in<Container> is_in(const Container& c)
{
return detail::is_in<Container>(c);
}