【发布时间】:2020-07-06 19:58:34
【问题描述】:
#include<iostream>
#include<string.h>
using namespace std;
string revString(string s,string copy,int i,int j)
{
if(i==s.length())
return copy;//if 'i' reaches to the length of the string it returns the copied value
else{
copy[i]=s[j];//copying the string s into copy
return revString(s,copy,++i,--j);// calling recursively
}
}
int main()
{
string s,copy;
cout<<"Enter a string without entering spaces\n";
cin>>s;
int i=0,j=s.length()-1;
cout<<revString(s,copy,i,j);//function for reversing the string
return 0;
}
这里我尝试使用递归将字符串 's' 复制到字符串 'copy' 中,但该函数没有返回任何内容。
【问题讨论】:
-
在每次迭代时打印
copy,您应该能够弄清楚发生了什么。 -
字符串在分配给不存在的元素时不会展开。相反,行为是未定义的。
-
std::string rev{s.rbegin(), s.rend()};? -
revString(s,s,i,j);应该解决 molbdnilo 报告的问题。 -
添加
if (copy.length() == 0) copy.resize(s.length());
标签: c++ string algorithm recursion reverse