C
compulim
Hi Tomer,
If there's a non-recursive alternative, you should never use recursive
function. (easier to maintain, performance reason...)
The following implementation provide non-recursive approach with no hacking
(or "special case handling"), lesser function calls and zero IF statement.
public static string StrRev( string s ) {
char[] charArray;
charArray = s.ToCharArray();
Array.Reverse( charArray );
return ( new string( charArray ) );
}
Compulim @ kasuei
Hi,
I've check on the web for a string reverse function and this one on many
places:
public static string StrRev(string s)
{
if (s.Length == 1)
return s;
else
return StrRev( s.Substring(1) ) + s.Substring(0,1);
}
Now, this doesn't work when you put an empty string and produce a
StackOverflowException, so we add a condition at the begining of the
function:
public static string StrRev(string s)
{
if (s.Length == 0)
return s;
if (s.Length == 1)
return s;
else
return StrRev( s.Substring(1) ) + s.Substring(0,1);
}
Hope this helps, Tomer.
If there's a non-recursive alternative, you should never use recursive
function. (easier to maintain, performance reason...)
The following implementation provide non-recursive approach with no hacking
(or "special case handling"), lesser function calls and zero IF statement.
public static string StrRev( string s ) {
char[] charArray;
charArray = s.ToCharArray();
Array.Reverse( charArray );
return ( new string( charArray ) );
}
Compulim @ kasuei
Hi,
I've check on the web for a string reverse function and this one on many
places:
public static string StrRev(string s)
{
if (s.Length == 1)
return s;
else
return StrRev( s.Substring(1) ) + s.Substring(0,1);
}
Now, this doesn't work when you put an empty string and produce a
StackOverflowException, so we add a condition at the begining of the
function:
public static string StrRev(string s)
{
if (s.Length == 0)
return s;
if (s.Length == 1)
return s;
else
return StrRev( s.Substring(1) ) + s.Substring(0,1);
}
Hope this helps, Tomer.