(C++) StringToNewick
January 7, 2018 · View on GitHub
(C++) StringToNewick
StringToNewick is a Newick code snippets to convert a well formed Newick std::string to Newick std::vector<int>.
struct BinaryNewickVector { enum { bracket_open = -1 }; enum { bracket_close = -2 }; enum { comma = -3 }; enum { new_line = -4 }; enum { null = -5 }; }; ///StringToNewick converts a std::string to a Newick std::vector<int>. ///StringToNewick assumes that the input is well-formed and ///has both trailing and tailing brackets. ///From http://www.richelbilderbeek.nl/CppNewickToVector.htm const std::vector<int> StringToNewick(const std::string& newick) { assert(!newick.empty() && "s must not be empty"); assert(newick[ 0]=='(' && "s must begin with a '('"); assert(newick[newick.size()-1]==')' && "s must end with a ')'"); std::vector<int> v; int value = 0; BOOST_FOREACH(const char i,newick) { if (i == '(') { if (value!=0) v.push_back(value); value = 0; v.push_back(BinaryNewickVector::bracket_open); continue; } if (i == ')') { if (value!=0) v.push_back(value); value = 0; v.push_back(BinaryNewickVector::bracket_close); continue; } if (i == ',') { if (value!=0) v.push_back(value); value = 0; continue; } assert(i >= '0' && i <= '9'); //Should be a number value*=10; value+=boost::lexical_cast<int>(i); } assert(value == 0 && "Final bracket close must set value to zero"); return v; }