将特定字符移动到字符串末尾的递归 C++ 函数 [英] Recursive C++ Function To Move Specific Characters To End Of String

查看:56
本文介绍了将特定字符移动到字符串末尾的递归 C++ 函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个递归函数,在给定一个字符串的情况下,该函数递归地计算一个新字符串,其中所有小写的x"字符都已移动到字符串的末尾.

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.

例如,
moveXs("xxre") --> "rexx"
moveXs("xxhixx") --> "hixxxx"
moveXs("xhixhix") --> "hihixxx"

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

我对 C++ 比较陌生,尤其是递归(不幸的是函数必须使用这种方法来解决问题),所以我在这个问题上遇到了麻烦.下面是我迄今为止编写的代码,但它似乎只返回空字符串,我终生无法弄清楚原因.

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!

推荐答案

看起来您刚刚遇到了一些索引问题.我在这里修改了你的代码,并注意新的回报.我也摆脱了多余的第二个字符串.

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()));
    }
}

您可以在这里看到它的实际效果:http://ideone.com/aT75l5

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

这篇关于将特定字符移动到字符串末尾的递归 C++ 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆