Method I.
///// Call- ReverseString('gfedcba',
0);
///// Result- ReverseString - gfedcba
///// Call- ReverseString('abcdefg');
///// Result- ReverseString - gfedcba
///// Call- ReverseString('abcdefg');
///// Result- ReverseString - gfedcba
///// Call- ReverseString('abcdefg');
//Recursion
method; simple, for small strings
public string
ReverseString(string str)
{
if (str.Length <= 1) return str;
else return
ReverseString(str.Substring(1)) + str[0];
}
///// Result- ReverseString - gfedcba
Method II.
//Recursion
method; Need to starting index as 0, for
long strings
public string
ReverseString(string str, int Chrindex)
{
char[] chr = str.ToCharArray();
int len = chr.Length;
if (Chrindex < len / 2)
{
char c = chr[Chrindex];
chr[Chrindex] = chr[len -
Chrindex - 1];
chr[len - Chrindex - 1] = c;
Chrindex++;
return ReverseString(new string(chr),
Chrindex);
}
else
{
return new string(chr);
}
}
Method III.
//Using Another
array, need to traverse full array.
public string
ReverseString(string str)
{
char[] chr = str.ToCharArray();
char[] result = new char[chr.Length];
for (int i = 0, j
= str.Length - 1; i < str.Length; i++, j--)
{
result[i] = chr[j];
}
return new string(result);
}
Method IV.
//Using swap method; need to traverse only half of the array.
public string
ReverseString(string str)
{
char[] chr = str.ToCharArray();
for (int i = 0, j
= str.Length - 1; i < j; i++, j--)
{
char c = chr[i];
chr[i] = chr[j];
chr[j] = c;
}
return new string(chr);
}