Search code examples
c++recursion

Appending strings then storing them into a vector


I'm confused on where my logic for my function is incorrect. The goal is to return a vector of type string (vector<string>) where the characters of two different strings are paired up based on their indexes. This process would continue until the end of each string. For instance, given the variables below:

string strOne = "shop";
string strTwo = "fast";
vector<string> vec;


// when the program runs, vec should return {"sf", "ha", "os", "pt"}
// the first index of each string is paired together (e.g., "s" for strOne and "f" for strTwo) and added onto the *vec* variable
// the second index of each string is paired together (e.g., "h" for strOne and "a" for strTwo) and added onto the *vec* variable, etc

This is what I got so far:

vector<string> function1(string strOne, string strTwo, int i) 
{
    string result;
    vector<string> strVec;

    if (strOne.size() == 0 && strTwo.size() == 0) 
    {
        return strVec;
    } 

    if (i == 0) 
    {
        result = strOne.at(i) + strTwo.at(i);
        strVec.push_back(result);
        return strVec;
    } 
    else 
    {
        strVec = function1(strOne, strTwo, i- 1);
        result= strOne.at(i) + strTwo.at(i);
        strVec.push_back(result);
        return strVec;
    }
}


vector<string> function1(string strOne, string strTwo) {
    return function1(strOne, strTwo, strOne.size() - 1);
}

I created another function of the same name to be able to pass in more variables. From there, I created an if statement within that function to return an empty vector if both the strings are of size 0. For my case, I used the iterating int variable i to go into each string, then concatenate them into another string variable. I then added the string onto the declared vector variable. I would use recursion (required) to loop the process until it reaches the base case (the i == 0 if statement). In the other function with less parameters, I call the other function that does the work.

Where is the fault in my logic?


Solution

  • Adding chars together does not behave how you are expecting. Let's say strOne[i] is A (65) and strTwo[i] is B (66). The result of strOne[i] + strTwo[i] is the character ƒ (131). result = strOne[i] + strTwo[i] then converts this character into a one-character string. Instead try

    result = strOne[i];
    result += strTwo[i];