/// <summary>
/// 数组全部反转
/// </summary>
/// <param name="array"></param>
public static void ArrayReverse(int[] array)
{
if (array == null)
{
throw new ArgumentNullException("array", "array不能为null");
}
//算法1:自定义方法
int[] newArray = new int[10];
for (int i = 0; i < array.Length; i++)
{
newArray[i] = array[array.Length - 1 - i];
}
foreach (var i in newArray)
{
Console.Write(i + " ");
}
Console.ReadLine();
//算法2:类库自带方法
Array.Reverse(array);
foreach (var i in array)
{
Console.Write(i + " ");
}
Console.ReadLine();
//算法3:运用栈后进先出特性
Stack stack = new Stack();
foreach (var i in array)
{
stack.Push(i);
}
for (int i = 0; i < array.Length; i++)
{
array[i] = Convert.ToInt32(stack.Pop());
}
foreach (var i in array)
{
Console.Write(i + " ");
}
Console.ReadLine();
}
/// <summary>
/// 数组局部反转
/// </summary>
public static void ArrayReverse(int[] array, int begin, int end)
{
if (array == null)
{
throw new ArgumentNullException("array", "array不能为null");
}
if (begin < 0)
{
throw new ArgumentOutOfRangeException("begin", "begin不能小于0");
}
if (end < begin)
{
throw new ArgumentOutOfRangeException("end不能小于begin", (Exception)null);
}
if (end > array.Length)
{
throw new ArgumentOutOfRangeException("end", "end超过array最大下标");
}
//算法1:自定义方法
while (end > begin)
{
int temp = array[begin];
array[begin] = array[end];
array[end] = temp;
begin++;
end--;
}
foreach (var i in array)
{
Console.Write(i + " ");
}
Console.ReadLine();
//算法2:类库自带方法
Array.Reverse(array, begin, end);
foreach (var i in array)
{
Console.Write(i + " ");
}
Console.ReadLine();
}
/// <summary>
/// 字符串全部反转
/// </summary>
public static void StringReverse()
{
string str = "0123456789";
string newStr = "";
for (int i = 0; i < str.Length; i++)
{
newStr += str.Substring(str.Length - 1 - i, 1);
}
Console.WriteLine(newStr);
Console.ReadLine();
}