C ++在多个子字符串上拆分字符串

时间:2011-12-13 21:03:05

标签: c++ string boost

在C ++中,我想要类似于:

Split on substring

但是,我想指定要分割的多个子字符串。例如,我想将字符串“fda + hifoolkjba4”的“+”,“foo”,“ba”拆分为“fda”,“hi”,“lkj”,“4”的向量。有什么建议?最好是在STL和Boost中(如果可以避免的话,我宁愿不要加入Qt框架或其他库)。

2 个答案:

答案 0 :(得分:3)

我会使用正则表达式,来自<regex><boost/regex.hpp>;你需要的正则表达式就像(.*?)(\+|foo|ba)(加上最终的标记)。

以下是使用Boost的简化示例:

  std::string str(argv[1]);

  boost::regex r("(.*?)(\\+|foo|ba)");
  boost::sregex_iterator rt(str.begin(), str.end(), r), rend;

  std::string final;

  for ( ; rt != rend; ++rt)
  {
    std::cout << (*rt)[1] << std::endl;
    final = rt->suffix();
  }
  std::cout << final << std::endl;

答案 1 :(得分:1)

我建议在boost中使用正则表达式支持。有关示例,请参阅here

这是一个可以拆分字符串的示例代码:

#include <iostream>
#include <boost/regex.hpp>

using namespace std;    

int main()
{

    boost::regex re("(\\+|foo|ba)");
    std::string s("fda+hifoolkjba4");

    boost::sregex_token_iterator i(s.begin(), s.end(), re, -1);
    boost::sregex_token_iterator j;
    while (i != j) {
       std::cout << *i++ << " ";
    }
    std::cout << std::endl;
    return 0;
}
相关问题