Hi,
The program I'm trying to make is to transcribe DNA to RNA and separate into codons.
So far I was able to transcribe DNA to RNA and store it in string variable.
Next part is to separate RNA strand into groups of 3 (codon) and store each group in vector.
Below is part of my code.

``````void GeneLoader::setCodon ()
{
string s = rna.getRnaStrand ();

for (int i=0; i < s.length() - 2; i+3)
{
temp = s[i] + s[i+1] + s[i+2];
s.push_back (temp);
}
}``````

The string s has the RNA sequence stored inside. I'm trying to concatenate s + s[i+1] + s[i+2] into a one string and store into the vector.
For example, if s == 'a', s[i+1] == 'c', s[i+2] == 'g' then s + s[i+1] + s[i+2] would equal to "acg". The "acg" would be stored into the vector and so forth.
Any advice on how to tackle this problem?

## All 3 Replies

`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 ;
}
``````

I'm a beginner in c++.
I have tried your code but it didn't work.
Also I don't understand the need for "std::string::size_type i = 0".

> I don't understand the need for "std::string::size_type i = 0".