【发布时间】:2014-03-01 12:34:50
【问题描述】:
我有一个这样的字符串:
std::string input = "This* #is # #just# a *random ##string #*that#
may contain any# char*cters#";
我需要获取所有子字符串:
1) 字符'#'之间
与
2) 包含字符'*'
结果将是:
" a *random "
"*that"
" char*cters"
我是这样做的:
std::vector<std::string> substrings;
boost::split(substrings, input, boost::is_any_of("#"));
for (int i = 0; i < substrings.size(); i++)
{
if (i != 0 // first and last substring is not between '#' (only from one side)
&& (i != substrings.size() - 1)
&& !substrings[i].empty()
&& substrings[i].find('*') != std::string::npos) // if contain '*' character
{
// Here I've got my result
}
}
它有效,但有什么有效的解决方案可以做到这一点?
【问题讨论】:
-
如果你想用更少的代码做到这一点,你需要一个正则表达式库。如果你想用更少的 cpu 时间来做到这一点,你应该用你自己的代码迭代字符串来拆分。
-
在您的代码中,如果您从
1开始循环并在substrings.size() - 1结束,则循环中不需要这两个条件。并且由于空字符串不包含'*',您还可以删除empty条件。