-5

编写一个程序,提示用户输入字符串并使用递归函数向后打印字符串。不要使用任何全局变量;使用适当的参数。你能给我一些提示吗,比如伪代码?

int stringbackwards(string a){                  
if()


else


}


int main(){

    string name;

    cout<<"Write a name: ";           
    cin>>name;

    cout<<"Backwards "<<stringbackwards(name);

    return 0;
}
4

2 回答 2

4

你为什么要使用递归呢?c++ 中有一个很好的概念,称为迭代器,它已经具有此功能实现 :)

http://www.cplusplus.com/reference/string/string/rbegin/

所以在你的情况下:

cout<<"Backwards ";
for (std::string::reverse_iterator rit=name.rbegin(); rit!=name.rend(); ++rit)
{
    cout << *rit;
}

但是为了使其递归,我会这样做(伪代码)。

function backwards(std::string& name, unsigned int length)
{
    unsigned int length = name.length();
    unsigned int currLength = length - 1;

    if (length > 0)
    {
         backwards(name, currLength);
    }

    std::cout << name[length - currLength - 1];
}
于 2013-10-25T09:42:34.857 回答
0

暗示:

假设字符串是“abcd”。您想打印“dcba”。换句话说,您首先打印最后一个字母。

因此,您将首先深入递归,然后在返回后打印字母“a”。

于 2013-10-25T09:38:57.867 回答