尝试在C ++中反转字符串,但返回相同的字符串 [英] Trying to reverse a string in C++ but getting the same string back

查看:124
本文介绍了尝试在C ++中反转字符串,但返回相同的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试在C ++中反转它时,我会得到相同的字符串。

I get the same string back when I try to reverse it in C++.

我读到递归是反转事物的好方法。我尝试通过返回字符串的第一个字符并在删除第一个字符的情况下调用相同的函数来实现递归算法,直到字符串的大小为1。我的第一个函数删除了字符串的第一个字符,第二个函数将其反转:

I read that recursion is a good way to reverse things. I tried to implement a recursive algorithm by returning the first character of the string and calling the same function with the first character removed until the string has a size of 1. My first function removes the first character of the string and the second function reverses it:

string deleteFirstElement(string input) {

    if (input.size() == 1) {
        return input;
    }

    // This loop brings the first element to the last position
    for (int i = 0; i < input.size()-1; i++) { 
        char temp;
        temp = input.at(i);
        input.at(i) = input.at(i+1);
        input.at(i + 1) = temp;
    }

    input.pop_back();   // Delete last element of the string
    return input;
}

string reverseit(string input) {
    if (input.size() == 1) {
        return input;
    }
    else {
        return input.at(0) + reverseit(deleteFirstElement(input));
    }
}

但是为什么我要返回相同的字符串却没有

But why do I get the same string back and no reverse?

推荐答案

您会得到相同的字符串,因为您再次构建了相同的字符串。
使用 ABC的示例,您将看到函数的作用:

You get the same string back because you build the same string again. Using the example of "ABC" you'll see what the function does:

reverseit( ABC)返回'A'+ reverseit( BC )

reverseit( BC)返回'B'+ reverseit( C)

reverseit( C)返回'C'

reverseit("ABC") returns 'A' + reverseit("BC")
reverseit("BC") returns 'B' + reverseit("C")
reverseit("C") returns 'C'

您想要的

char firstChar = input.at(0);
return  reverseit(deleteFirstElement(input)) + firstChar;

但实际上您应该考虑其他解决方案。递归

But really you should be looking into another solution. Recursion


  • 降低可读性

  • 很慢

  • 使用大量的堆栈内存

  • 容易创建难以调试的无限循环

  • reduces readability
  • is slow
  • uses lots of stack memory
  • easily creates hard to debug endless loops

通常尽可能避免。当然,有些解决方案确实很优雅,但是循环几乎总是更快。

in general it should be avoided if possible. Some solutions are really elegant with it, to be sure, but loops are almost always faster.

这篇关于尝试在C ++中反转字符串,但返回相同的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆