c++ - 如何拆分字符串并在 C++ 中得到我想要的?

标签 c++ bioinformatics

有这样一个字符串:M90I4D7

我需要将它插入这种结构:

struct  CigarOp {

    char     Type;   //!< CIGAR operation type (MIDNSHPX=)
    uint32_t Length; //!< CIGAR operation length (number of bases)

    //! constructor
    CigarOp(const char type = '\0', 
            const uint32_t& length = 0)
        : Type(type)
        , Length(length) 
    { }
};

这意味着我需要将它分成 3 组,每组都是一个 CigarOp( 'M' ,90 'I', 4 'D' ,7 )

最佳答案

假设字符串的形式为 ([A-Z][0-9]+)*,您可以非常简单地执行如下操作:

#include <sstream>

...

std::vector<CigarOp> cigars;
std::istringstream parser("M90I4D7");

char c;
std::uint32_t l;

while(parser >> c >> l) {
  cigars.push_back(CigarOp(c, l));
}

请注意,此代码不执行任何类型的验证。如果需要验证,实现它的一种方法是使用 Boost.Spirit(在 http://boost.org 上找到):

#include <boost/spirit/include/qi.hpp>
#include <boost/fusion/adapted/struct.hpp>

#include <cstdint>
#include <iostream>

struct CigarOp {
  char          Type;
  std::uint32_t Length;
};

BOOST_FUSION_ADAPT_STRUCT(CigarOp, (char, Type) (std::uint32_t, Length))

int main() {
  using boost::spirit::qi::phrase_parse;
  using boost::spirit::qi::char_;
  using boost::spirit::qi::uint_;
  using boost::spirit::qi::standard::space;

  std::vector<CigarOp> cigars;

  std::string s = "M90I4D7";
  std::string::const_iterator first = s.begin(), last = s.end();

  bool r = phrase_parse(first, last, *(char_ >> uint_), space, cigars);

  if(r && first == last) {
    // string was well-formed
    for(auto const &cigar : cigars) {
      std::cout << cigar.Type << ", " << cigar.Length << '\n';
    }
  }
}

关于c++ - 如何拆分字符串并在 C++ 中得到我想要的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27055520/

相关文章:

c++ - flood fill 获取和 RGB 值

python - 将包含字符串的文件转换为 float ,然后添加它们

regex - 如何匹配两个 .csv 文件并写入第三个文件,用文件 1 中的数据替换文件 2 中的数据

python - Snakemake:是否可以使用目录作为通配符?

c++使用结构指针的段错误

c++ - 只有一种 Material 应用于多个对象

c++ - 对于类中动态大小的数组,std::vector 是否优于堆数组?

c++ - 使用标准库构建/解析 UTC 日期

python - 是否可以在 Snakemake 中有一个可选的输出文件?

python - 将 csv 转换为 Newick 树