一维数组
声明的同时为数组分配内存(初始化)
int []month = new int[12]{,,,,};
二维数组
int[,] myarr;
int[,] = new int[2,4];
遍历数组
可以使用foreach语句实现数组的遍历功能
namespace ConsoleApp1
{
class Program
{
static void Main()
{
int[] arr = new int[10] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
foreach(int number in arr)
{
Console.WriteLine(number);
}
}
}
}
添加数组元素
namespace ConsoleApp1
{
class Program
{
static int[] AddArray(int[] ArrayBorn,int Index,int Value)
{
if (Index >= (ArrayBorn.Length))
Index = ArrayBorn.Length - 1;
int[] TemArray = new int[ArrayBorn.Length + 1];
for(int i = 0; i < TemArray.Length; i++)
{
if (Index >= 0)
{
if (i < (Index + 1))
TemArray[i] = ArrayBorn[i];
else if (i == (Index + 1))
TemArray[i] = Value;
else
TemArray[i] = ArrayBorn[i - 1];
}
else
{
if (i == 0)
TemArray[i] = Value;
else
TemArray[i] = ArrayBorn[i - 1];
}
}
return TemArray;
}
static void Main()
{
int[] ArrayInt = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
Console.WriteLine("原数组元素:");
foreach (int i in ArrayInt)
Console.Write(i + "");
Console.WriteLine();
ArrayInt = AddArray(ArrayInt, 4, 5);
Console.WriteLine("插入之后的数组元素:");
foreach (int i in ArrayInt)
Console.Write(i + "");
}
}
}
原数组元素:
0123456789
插入之后的数组元素:
01234556789
删除数组元素
用删除元素后面的元素覆盖要删除的元素(不改变原长度)
namespace ConsoleApp1
{
class Program
{
static void DeleteArray(string[] ArrayBron,int Index,int Len)
{
if (Len <= 0)
{
return;
}
if (Index == 0 && Len >= ArrayBron.Length)//超出范围
{
Len = ArrayBron.Length;
}
else if ((Index + Len) >= ArrayBron.Length)
{
Len = ArrayBron.Length - Index - 1;
}
int i = 0;
for (i = 0; i < ArrayBron.Length - Index - Len; i++)//遍历删除的长度
ArrayBron[i + Index] = ArrayBron[i + Len + Index];//覆盖
for (int j = (ArrayBron.Length - 1); j > (ArrayBron.Length - Len - 1); j--)
ArrayBron[j] = null;
}
static void Main()
{
string[] ArrayStr = new string[] { "m", "r", "s", "f", "o", "t" };
Console.WriteLine("源数组:");
foreach (string i in ArrayStr)
Console.Write(i + "");
Console.WriteLine();
DeleteArray(ArrayStr, 0, 1);
Console.WriteLine("删除数组后的元素:");
foreach (string i in ArrayStr)
Console.WriteLine(i + "");
}
}
}
删除后数组长度减n
namespace ConsoleApp1
{
class Program
{
static void DeleteArray(string[] ArrayBron,int Index,int Len)
{
if (Len <= 0)
{
return;
}
if (Index == 0 && Len > ArrayBron.Length)//超出范围
{
Len = ArrayBron.Length;
}
else if ((Index + Len) >= ArrayBron.Length)
{
Len = ArrayBron.Length - Index - 1;
}
int i = 0;
for (i = 0; i < ArrayBron.Length - Index - Len; i++)//遍历删除的长度
ArrayBron[i + Index] = ArrayBron[i + Len + Index];//覆盖
for (int j = (ArrayBron.Length - 1); j > (ArrayBron.Length - Len - 1); j--)
ArrayBron[j] = null;
}
static void Main()
{
string[] ArrayStr = new string[] { "m", "r", "s", "f", "o", "t" };
Console.WriteLine("源数组:");
foreach (string i in ArrayStr)
Console.Write(i + "");
Console.WriteLine();
DeleteArray(ArrayStr, 0, 1);
Console.WriteLine("删除数组后的元素:");
foreach (string i in ArrayStr)
Console.WriteLine(i + "");
}
}
}
数组排序
Array.Sort方法用于对一维数组中的元素进行排序
Array.Reverse方法用于反转一维数组或部分数组中元素的顺序
Array.Sort(arr);
Array.Reverse(arr);