Search code examples
c++stringconcatenationgmp

Concatenating Strings for 3 or More Elements in C++ (string[i]+string[i+1]+string[i+2])


I'm having a hard time trying to learn how to concatenate a string with 3 or more elements. Here is the code that I am working on now:

string msgASCII, conHolder;    
for (int i = 0; i < msgASCII.length(); i = i + 3) { 
        conHolder = msgASCII[i] + msgASCII[i+1] + msgASCII[i+2];    

This code doesn't seem to work as inteded. What I'm trying to do is make conHolder = the first three elements of my string msgASCII. So if msgASCII = 083097109 (for SAM in ASCII), then I want to make conHolder = "083" so I can turn that back to char later.

I also tried doing this:

for (int i = 0; i < msgASCII.length(); i = i + 3) { 
        concatenateHolder = msgASCII[i] + msgASCII[i+1] + msgASCII[i+2];
        concatenateHolder2 = concatenateHolder + msgASCII[i+2];

But concatenateHolder would return h and concatenateHolder2 would return h3.

EDIT: I think I might have found a solution which I posted below! Thanks also to Fred for the substring method. I'll most likely be using that instead.


Solution

  • I think I might have found a solution to my question. For a little more information though, msgASCII, conHolder, and the concatenateHolders are both of type string.

    One solution is what Fred Larson said, to use std::string::substr. I think I might go with that as that seems very convenient.

    Another way I found out but haven't tested is to multiply the first value [0] by 100, the second [1] by 10, and the third [2] by 1 (or no need to multiply at all), and then add them together. I have not tried this code yet, but I think it should work!