使用递归算法使字符串s倒序。

使用递归算法使字符串s倒序。
string daoxu(string &str){
static string news;
static int length=str.length();
length--;
if(length<0){
str.swap(news);
return str;
}else{
news+=str.substr(length,1);
// cout<<news<<" ";
daoxu(str);
}
return str;
}

int main(){
string str;
cin>>str;
cout<<daoxu(str);
}

1、使用静态变量,递归时,局部变量只会初始化第一次;
2、利用原字符串的长度、substr()函数来从原字符尾取字符,每次递归length的值减1,再取前一个字符;
3、当length的值小于0时,递归结束,将结果值传回主函数。

posted on 2022-07-16 10:31  zwhyh  阅读(157)  评论(0)    收藏  举报

导航