Write a recursive, string -valued function, reverse, that accepts a string and r
ID: 3670964 • Letter: W
Question
Write a recursive, string -valued function, reverse, that accepts a string and returns a new string consisting of the original string in reverse. For example, calling reverse with the string goodbye returns the string eybdoog.
Reversing a string involves:
No action if the string is empty or has only 1 character (reversing a single character string does not change anything). Thus for empty and 1-character strings , the reversed string is just the string itself.
Otherwise concatenate the last character with the result of reversing the string consisting of the second through the next-to-last character , followed by the first character . In the above example, you would concatenate the 'e' (last character of goodbye) with the result of calling reverse on oodby (the string from the second character to the next-to-last), with the 'g' (first character ).
Explanation / Answer
#include<iostream.h>
#include<iomanip.h>
void reversel(string& i, int a, int b)
{
if(a >= b)
{
return;
}
char tmp;
tmp = i[a];
i[a]=i[b];
i[b]= tmp;
a++;
b--;
reversel(i,a,b);
}
void strreverse(string& i)
{
reversel(i,0, i.length()-1);
}
int main()
{
cout<<"Please enter the string which you want to be reversed: ";
string a;
cin>>a;
strreverse(a);
cout<<a<<endl;
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.