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();
}
}
- How does this program works?
- Does the statement
rsOb.DisplayRev(s);callDisplayRev(str.Substring(1, str.Length-1));for every Character in the string?
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
Recursionto 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
substringof"hello"which will be"ello"Note that the call to the Console.WriteLine hasn’t been made, because the function
DisplayRevhas 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”, theConsole.WriteLinecode will be hit writing the “o” to the console, this function will then be exited and the caller of that will then hit theConsole.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