Inversión de una cuerda

I was just researching how can I reverse a String. I found a Program in C# The Complete Reference Book but i was not able to understand it. Plz anyone Explain me how it works

The Program is here:

using System;
class RevStr 
    // Display a string backward.
    public void DisplayRev(string str) 
        if(str.Length > 0)
            DisplayRev(str.Substring(1, str.Length-1));


class RevStrDemo 
    static void Main() 
        string s = "this is a test";
        RevStr rsOb = new RevStr();
        Console.WriteLine("Original string: " + s);
        Console.Write("Reversed string: ");
  1. How does this program works?
  2. Does the statement rsOb.DisplayRev(s); llámenos al DisplayRev(str.Substring(1, str.Length-1)); for every Character in the string?

preguntado el 02 de febrero de 12 a las 11:02

It is an example of recursion. Presumably the book talks about recursion? -

We will not explain the todo program. Please tell us exactamente what you are not understanding. -

9 Respuestas

What I'd Recommend

¿Has probado myString.Reverse();

It would be the easiest way to reverse a string in C# (.Net 3.5 and above).


As for your example it is using Recursion to display each character by removing the end character (by creating a substring of the original with the first char removed) then calling itself again until there are no characters remaining.

You will only need to call DisplayRev(s); once because it recursively displays each character within.

Explanation Attempt

For example we have the string "hello".

The first call will recursively call the function with the substring of "hello" Cuál podría ser "ello"

Note that the call to the Console.WriteLine hasn't been made, because the function DisplayRev has been called so we then step in to the recursive call.

This will keep on occuring until the string is empty (.Length == 0). Then the function will exit and return to the caller, which will be where the string[0] is "o", the Console.WriteLine code will be hit writing the "o" to the console, this function will then be exited and the caller of that will then hit the Console.WriteLine, which will be the "l", this will keep returning until the initial call is reached.

Thus resulting in your initial string, reversed.


There are a number of tutorials around about recursion. Here's a few (they'll be better at explaining it than I am):

Recursion Example 1
Recursion Example 2

Respondido 02 Feb 12, 15:02

Obviously this code is not an example of how to reverse a string. It's a demonstration of recursion! And yet the up-votes flow! - David Heffernan

The crocodiles were out before I had chance to complete my answer today! - Lloyd Powell


Utiliza recursiva llamadas

DisplayRev calls itself with one less char

when it get to the end , and en aquel entonces from the recursion - it prints the char.

Also notice that its just display the reveresed string and no actually revere it

Respondido 02 Feb 12, 15:02

What is happening inside there in class.look carefully
See there is Sub-string function is calling with two parameters.

  1. is length of string[here is only a char]
  2. position in string
    and then it print that char. and its a recursive call so it happens until string length is non zero.

Respondido 02 Feb 12, 15:02

It's a recursive call to the same function.

Basically it relies on the fact that the Console.Write command isn't called until the previous call to DisplayRev ha regresado.

Each call to DisplayRev is passed a string that is has had the first character removed: For

str = "abcdef"
str.Substring(1, str.Length-1)

da "bcdef"

The Console command writes the first character (str[0]).

By the time that the last DisplayRev call is processed str[0] is "f".

All calls then wind back to the first call, with lots of displays e.g.:


Respondido 02 Feb 12, 15:02

Why don't you use the built-in functionality of string?

string s =  "123";
s = s.Reverse();

Respondido 02 Feb 12, 15:02

The answer to that question is that @user is trying to learn about recursion - David Heffernan

This program simply outputs the string reversed, it does not modify the string in any way. Here is how it works - it is based on recursion. If you print the reverse of the substring of the initial one starting at position 1(i.e. str.Substring(1, str.Length-1)) and then print the first character of the string you will end up with your whole string being reversed. Obviously the function is correct for strings of length 1 and after that you can prove using induction and the above observation that the given function will print the string reversed correctly for all lengths.

However there is a built-in function to reverse a string if you do not insist on implementing it yourself:


Respondido 02 Feb 12, 15:02

Haz una carrera en seco:

input string = "This is a test";

Recursive reverse function called:

public void DisplayRev(string str)      
    if(str.Length > 0)             
        DisplayRev(str.Substring(1, str.Length-1));


Stack call with argument are as follows:

DisplayRev("t")             // ----> prints "t"

DisplayRev("st")            // ----> prints "s" ----> complete string "ts"

DisplayRev("est")           // ----> prints "e" ----> complete string "tse"

DisplayRev("test")          // ----> prints "t" ----> complete string "tset"

DisplayRev(" test")         // ----> prints " " ----> complete string "tset "

DisplayRev("a test")        // ----> prints "a" ----> complete string "tset a"

DisplayRev(" a test")       // ----> prints " " ----> complete string "tset a "

DisplayRev("s a test")      // ----> prints "s" ----> complete string "tset a s"

DisplayRev("is a test")     // ----> prints "i" ----> complete string "tset a si"

DisplayRev(" is a test")    // ----> prints " " ----> complete string "tset a si "

DisplayRev("s is a test")   // ----> prints "s" ----> complete string "tset a si s"

DisplayRev("is is a test")  // ----> prints "i" ----> complete string "tset a si si"

DisplayRev("his is a test") // ----> prints "h" ----> complete string "tset a si sih"

DisplayRev("This is a test")// ----> prints "t" ----> complete string "tset a si siht"

Respondido 02 Feb 12, 15:02

Reversing a String (Most efficient algorithm) : The following does not deal with UTF-16 surrogate pairs.

public static String reverse(String orig){
   char[] s = orig.ToCharArray();
   int n = s.Length;
   int halfLength = n / 2;
   for (int i = 0; i < halfLength; i++){
     char temp = s[i];
     s[i] = s[n - 1 - i];
     s[n - 1 - i] = temp;
    return new String(s);

Respondido 06 Jul 15, 10:07

Lots of people seem to want to do this… one neat way is to utilise Array.Reverse

Pass the string to a char array, use Array.Reverse then pass the char array back as a string.

Public static string ReverseString(string str)
char[] arr = str.ToCharArray();
return new string(arr);}

Respondido el 18 de junio de 18 a las 09:06

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.