【问题标题】:Efficient way to get all substrings from a string that contains special characters从包含特殊字符的字符串中获取所有子字符串的有效方法
【发布时间】: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 条件。

标签: c++ string boost


【解决方案1】:

您可以使用regular expression "#([^#*]*[*][^#]*)#" 来提取所有此类字符串。

该表达式描述了您要查找的子字符串类型:

  • # 开头
  • 有零个或多个除星号以外的字符,...
  • 后跟至少一个星号
  • 后跟零个或多个字符,而不是#
  • 最后是#

【讨论】:

  • 应该是"#([^#*]*[*][^#*]*)#"(正好是1个'*',里面没有'#')?或 "#([^#*]*[*][^#]*)#"(对于 1+ '*' 并且内部没有 '#')?
  • @Jarod42 是的,你是绝对正确的 - 我的表达式可以抓取带有 #s 的字符串,这不是 OP 想要的。谢谢指正!
猜你喜欢
  • 2020-08-26
  • 2015-07-16
  • 2020-07-12
  • 2020-12-25
  • 2010-11-10
  • 2021-08-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多