boost分割用单个字符或只是一个字符串 [英] boost split with a single character or just one string
问题描述
我希望在单个字符或字符串上拆分字符串。我想使用 boost :: split
,因为boost字符串是我们的基本字符串处理的标准(我不想混合几种技术)。
在单个字符的情况下,我可以做 split(vec,str,is_any_of(':'))
但我想知道如果有一种方法只指定一个字符。它可以提高性能,但更重要的是,我认为代码将更清晰只用一个字符,因为 is_any_of 传达一个不同的意思,我想要的。
为了匹配字符串,我不知道使用什么语法。我不想构造一个正则表达式;一些简单的语法如 split(vec,str,match_str(::)
将是好的。
在下面的代码中,为了简洁,让我假设使用命名空间boost
。
对于分割字符,如果只允许 algorithm / string
,
is_from_range
可能用于:
split(vec,str,is_from_range(':',':'));
或者,如果允许 lambda
:
split(vec,str,lambda :: _ 1 ==':');
或如果准备专用谓词是允许的:
struct match_char {
char c;
match_char(char c):c(c){}
bool operator()(char x)const {return x == c;}
};
split (vec,str,match_char(':'));
提到,
似乎没有办法用 split
。
如果允许 iter_split
,以下代码可能符合目的:
iter_split(vec,str,first_finder(::));
I wish to split a string on a single character or a string. I would like to use boost::split
since boost string is our standard for basic string handling (I don't wish to mix several techniques).
In the single character case I could do split(vec,str,is_any_of(':'))
but I'd like to know if there is a way to specify just a single character. It may improve performance, but more importantly I think the code would be clearer with just a single character, since is_any_of conveys a different meaning that what I want.
For matching against a string I don't know what syntax to use. I don't wish to to construct a regex; some simple syntax like split(vec,str,match_str("::")
would be good.
In the following code, let me assume using namespace boost
for brevity.
As for splitting on a character, if only algorithm/string
is allowed,
is_from_range
might serve the purpose:
split(vec,str, is_from_range(':',':'));
Alternatively, if lambda
is allowed:
split(vec,str, lambda::_1 == ':');
or if preparing a dedicated predicate is allowed:
struct match_char {
char c;
match_char(char c) : c(c) {}
bool operator()(char x) const { return x == c; }
};
split(vec,str, match_char(':'));
As for matching against a string, as David Rodri'guez mentioned,
there seems not to be the way with split
.
If iter_split
is allowed, probably the following code will meet the purpose:
iter_split(vec,str, first_finder("::"));
这篇关于boost分割用单个字符或只是一个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!