s[i] + s[i+1] + s[i+2];
would just do an integral addition of the three char values; instead you need to make a std::string
of three chars.
I suppose for (int i=0; i < s.length() - 2; i+3)
is a typo;
should be for( int i=0 ; i < s.length() - 2 ; i += 3 )
.
Something like:
std::vector< std::string > strand_to_codons( const std::string& strand )
{
std::vector< std::string > codons ;
for( std::string::size_type i = 0 ; i < strand.size() - 2 ; i += 3 )
{
const char temp[] = { strand[i], strand[i+1], strand[i+2], 0 } ;
codons.emplace_back(temp) ;
}
return codons ;
}
Another option would be to use the substr()
member function of std::string
:
std::vector< std::string > strand_to_codons( const std::string& strand )
{
std::vector< std::string > codons ;
for( std::string::size_type i = 0 ; i < strand.size() - 2 ; i += 3 )
codons.push_back( strand.substr( i, 3 ) ) ;
return codons ;
}
Yet another way is to construct the substring in situ into the std::vector<>
via an emplace_back()
(requires compiler support for variadic templates).
std::vector< std::string > strand_to_codons( const std::string& strand )
{
std::vector< std::string > codons ;
for( auto iter = strand.begin() ; iter < strand.end()-2 ; iter += 3 )
codons.emplace_back( iter, iter+3 ) ;
return codons ;
}