Reputation: 43
I want to reverse a string in C++ without using a loop or any other classes than std::string. Only the following methods should be used to reverse the string: x.at(); s.size()/s.length(); x.substr(pos,len); I think the usage of a recursion would be the solution to this problem, but I didn't figure it out how to do it right.
I tried this version, but it doesn't work.
string reverseWrapper(string str, int i, string stringToReturn) {
if(i < 0) return stringToReturn;
//cout << stringToReturn << '\n' << str.at(i) << '\n';
stringToReturn.push_back(str.at(i));
return reverseWrapper(str, int(str.size()) - 1, stringToReturn);
}
string reverseWithoutLoop(string str) {
string stringToReturn;
if(!(stringToReturn.length() == str.length())) {
return reverseWrapper(str, int(str.size()) - 1, stringToReturn);
}
return stringToReturn;
}
Can you help me solving this problem?
Upvotes: 1
Views: 1333
Reputation: 5138
You can reverse the string by recursively returning the reversed back half + the reversed front half of the string. You can stop when the string is shorter than 2.
string reverseWithoutLoop(string const& str) {
if( str.length() < 2 ){
return str;
}
return reverseWithoutLoop( str.substr( str.length()/2, str.length() ) )
+ reverseWithoutLoop( str.substr( 0, str.length()/2 ) );
}
See working version here
Upvotes: 2
Reputation: 2215
How about having a function starting with the original string and an empty reverse string. If the original and the reverse have the same length we are finished.
Else we call the function (and return the result) with the original and a concatenation of the current reverse plus the last character. The index of the last character we calculate by substracting the lengths of both strings (and don't forget to subtract 1 because it's 0-based).
Upvotes: 0