I'm trying to modify a string passing it by reference by reversing it ex: word dolphin to that it is nihplod using recurssion only. I can't add any more parameters to the function of modify its header. My output right now is od instead of dolphin , I think its only doing the last two letters, I honestly don't know why. Any thing that I should change? Here's my code.
void reverse(string &word) {
if (word.length() == 1 || word.length() == 0) {
if (word.length() == 1) {
word = word;
}
else if (word.length() == 0) {
word = "nothing to reverse";
}
}
else {
string temp;
if (temp.length() == 0) {
temp = "";
temp = temp+word.substr(word.length() - 1, 1);
word.pop_back();
if (word.length() == 0) {
word = temp;
}
else if (word.length() == 1) {
//temp = temp + word.substr(word.length() - 1, 1);
temp = temp + word;
word.pop_back();
word = temp;
}
else {
reverse(word);
}
}
else {
temp = temp + word.substr(word.length() - 1, 1);
word.pop_back();
if (word.length() == 0) {
word = temp;
}
else if (word.length() == 1) {
//temp = temp + word.substr(word.length() - 1, 1);
temp = temp + word;
word.pop_back();
word = temp;
}
else {
reverse(temp);
}
}
}
}
Algorithm is this:
reverse
on your substringHere you go:
void reverse(string& word)
{
size_t len = word.size();
if (len < 2)
{
return;
}
char first = word[0];
char last = word[len - 1];
string inner;
if (len > 2)
{
inner = word.substr(1, len - 2);
reverse(inner);
}
word = last + inner + first;
}
A non-recursive way of achieving the same thing could be:
void reverseString(std::string& input)
{
const size_t inputStringLength = input.size();
for (size_t index = 0; index < inputStringLength/2; ++index)
{
// swap the character at "index" position with the character at "inputStringLength - index - 1" position
input[index] ^= input[inputStringLength - index - 1] ^= input[index] ^= input[inputStringLength - index - 1];
}
}
void rev_recv(std::string& s, int from, int to) {
if (from >= to) return;
rev_recv(s, from + 1, to - 1);
std::swap(s[from], s[to]);
}
void reverse(string &word)
{
string temp = word;
if(temp.length != 0)
{
cout << temp.at(temp.length()-1);
reverse(temp.erase(temp.length()-1));
}
else
cout << "\ndone\n";
}
This will print in reverse and not modify the original string that was passed in. If you want the original string modified, just remove the temp
variable.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.