It’s common to come across a requirement to reverse an array or string recursively or iteratively. Even though C# has a linq method that does this for you. It s a good practice to understand how reversing works.
There are several ways you can reverse a collections. Below are two approaches to reverse an array and string, since string is a character array, same approach applies to them.
public static void RecursiveReverse(int [] arr, int start, int end)
{
if(start >= end)
{
return;
}
var temp = arr[end];
arr[end] = arr[start];
arr[start] = temp;
RecursiveReverse(arr, start + 1, end-1);
}
public static string Reverse(string str)
{
if(String.IsNullOrEmpty(str))
{
return string.Empty;
}
char[] c_str = str.ToCharArray();
for(int i = 0; i < str.Length / 2 ; i++)
{
var temp = c_str[i];
c_str[i] = c_str[str.Length - i - 1];
c_str[str.Length - i - 1] = temp;
}
return new string(c_str);
}
Recent Comments