Imp Programs

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 2

Three Ways to Reverse a String in C#

March 4, 2006, 11:09 am


OK, conceptually, it`s quite easy. A couple oI my Iriends got asked this question when
interviewing. Here are what my solutions are:
1. The trivial way
This is the probably the most trivial version:
public string Reverse1(string s)
,
char, c = s.ToCharArray();
string ts = string.Empty;
for (int i = c.Length - 1; i ~ 0; i)
ts c|i|.ToString();
return ts;
}
. Using a stack
This method is essentially the same as the Iirst one, however it uses the FILO nature oI the stack
to accomplish the same task.
public string Reverse(string s)
,
Stack<string stack = new Stack<string();
for (int i = 0; i s.Length; i)
stack.Push(s.Substring(i, 1));
string ts = string.Empty;
for (int i = 0; i s.Length; i)
ts stack.Pop();
return ts;
}
. Using recursion (The cool way)
This version is probably the coolest and might just be what your interviewer was looking Ior. It
actually does not need extra storage (it uses the stack but you do not need to programmatically
allocate space in your code like the previous two cases).
Here`s the how you would use the Reverse method:
public string Reverse(string s, int l)
,
if (l == 1)
return s;
else
return Reverse(s.Substring(1, s.Length - 1), -l) + s0,.ToString();
,
Heres the how you would use the Reverse method:
string s = ABCDEFGHIJK;
Console.WriteLine(Reverse(s, s.Length));

You might also like