一維二維陣列的建立與遍歷
阿新 • • 發佈:2019-02-04
一、一維陣列的建立與遍歷
方法一:
型別[ ]變數=new 型別[ ];l例如:string a=new string[ var int]
若使用new關鍵字,則方括號內必須宣告一個int型別的值來表示長度
也可以:string[ ] a=new string[ ]{ }
方法二:
string[ ] a={"a","b","c","d"};
一維陣列的遍歷:for和foreach
using System;
namespace practice3
{
classMainClass
{
publicstaticvoid Main(string[] args)
{
string[] a = newstring[]{ "huang", "jun", "kai", "h", "j", "k" };
for (int i = 0; i < a.Length; i++)
{
Console.WriteLine (a[i]);
}
foreach (string item in a)
{
Console.WriteLine (item);
}
}
}
}
二、二維陣列的建立與遍歷
方法一:
string[,] a=new string[5,3]
string[,] a=new string[5,3]{ {"a","b","c"},{"d","e","f"},{"g","h","i"},{"j","k","i"},{"l","m","n"}};
方法二:
string[, ] a={ {"a","b","c"},{"d","e","f"},{"g","h","i"},{"j","k","i"},{"l","m","n"}};
二維陣列的遍歷:for和foreach
知識點:GetUpperBound(int variable>維度數字<);獲取指定維度的上限
GetLowerBound(int variable>維度數字<);獲取指定維度的下限
using System;
namespace practice3
{
classMainClass
{
publicstaticvoid Main(string [] args)
{
string[,] a = newstring[,]
{ { "張三", "男", "18" }, { "李四", "女", "19" }, { "王五", "男", "18" } };
for (int i = 0; i < a.GetUpperBound (0)+1; i++)
{
for (int j = 0; j < a.GetUpperBound (1)+1; j++)
{
Console.Write(a[i,j]+"\t");
}
Console.WriteLine ();
}
}
}
}