Sarao
Sarao

Reputation: 379

Reversing a String

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));
        else
            return;

        Console.Write(str[0]);
    }
}

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

Upvotes: 2

Views: 4212

Answers (9)

ashish kadam
ashish kadam

Reputation: 60

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();
Array.Reverse(arr);
return new string(arr);}

Upvotes: 0

uday
uday

Reputation: 1

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);
}

Upvotes: 0

Azodious
Azodious

Reputation: 13872

Do a dry run:

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));
    else
         return; 

    Console.Write(str[0]);     
}

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"

Upvotes: 0

Lloyd Powell
Lloyd Powell

Reputation: 18790

What I'd Recommend

Have you tried myString.Reverse();

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

Response

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" which will be "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.

Reference

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

Upvotes: 6

ChrisBD
ChrisBD

Reputation: 9209

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 has returned.

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)

gives "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.:

Console.Write("f")
Console.Write("e")
Console.Write("d")
Console.Write("c")
Console.Write("b")
Console.Write("a")

Upvotes: 1

joshua
joshua

Reputation: 2371

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.

Upvotes: 1

Ivaylo Strandjev
Ivaylo Strandjev

Reputation: 70949

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:

str.Reverse();

Upvotes: 0

Dimi Takis
Dimi Takis

Reputation: 4959

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

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

Upvotes: 0

Royi Namir
Royi Namir

Reputation: 148574

No.

It uses Recursive calls

DisplayRev calls itself with one less char

when it get to the end , and back from the recursion - it prints the char.

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

Upvotes: 3

Related Questions