Search code examples
c++stringrecursion

Recursive C++ Function To Move Specific Characters To End Of String


I am attempting to write a recursive function that, given a string, recursively computes a new string where all the lowercase 'x' chars have been moved to the end of the string.

For example,
moveXs("xxre") --> "rexx"
moveXs("xxhixx") --> "hixxxx"
moveXs("xhixhix") --> "hihixxx"

I am relatively new to C++ and especially to recursion (unfortunately the function must employ this method to solve the problem), so I am having trouble with this problem. Below is the code I have written thus far, but it seems to be returning only empty strings and I can't for the life of me figure out why.

string moveXs(const string& str)
{
    string strCopy = str;
    if (strCopy.length() <= 1)
    {
        return str;
    }
    else if (strCopy[0] == 'x')
    {
        strCopy = strCopy.substr(1, strCopy.length() - 1) + str[0];
        return moveXs(strCopy.substr(0, (strCopy.length() - 2)));
    }
    else
    {
        return strCopy.substr(0, 1) + moveXs(strCopy.substr(1, strCopy.length() - 1));
    }
}

Any help or advice would be greatly appreciated!


Solution

  • Looks like you just had some indexing issues. I modified your code here, and note the new returns. Also I got rid of the extraneous second string.

    string moveXs(const string& str)
    {
        if (str.length() <= 1)
        {
            return str;
        }
        else if (str[0] == 'x')
        {
            return moveXs(str.substr(1, (str.length() - 1))) + str[0];
        }
        else
        {
            return str[0] + moveXs(str.substr(1, str.length()));
        }
    }
    

    You can see it in action here: http://ideone.com/aT75l5