數(shù)組1.一個存儲相同類型元素的固定大小的順序集合.?
缺點:大小預(yù)先確定不可更改,插入和刪除效率低.
2.數(shù)組是通過索引來訪問的.
3.由連續(xù)的內(nèi)存位置組成的.
數(shù)組的聲明:數(shù)據(jù)類型[] 數(shù)組名;
數(shù)組的賦值:初始化1.只初始化空間大小 2.既初始化空間大小 又為空間賦值
數(shù)組的默認值.
數(shù)字型的默認值:0 ; bool型的默認值:false; 字符型的默認值:\0 字符串型的默認值:null .
數(shù)組的賦值:大數(shù)據(jù)量的賦值
? ? ? ? ? ? int[] arr = new int[1000];
? ? ? ? ? ? Random r = new Random();
? ? ? ? ? ? for (int i = 0; i < arr.Length; i++)
? ? ? ? ? ? {
? ? ? ? ? ? ? ? arr[i] = r.Next(0, 1001);
? ? ? ? ? ? }
? ? ? ? ? ? for (int i = 0; i < arr.Length; i++)
? ? ? ? ? ? {
? ? ? ? ? ? ? ? Console.WriteLine(arr[i]);
? ? ? ? ? ? }
數(shù)組的操作:?1.查詢 :舉個例子來說 當我們要查詢某個同學(xué)的位置時,用數(shù)組來存儲數(shù)據(jù)是比較方便的:
string[] names = { "sss", "aaa", "bbb", "ccc" };
? ? ? ? ? ? int index = -1;
? ? ? ? ? ? console.writeline("輸入要查詢的名字");
? ? ? ? ? ? string key = console.readline();
? ? ? ? ? ? for (int i = 0; i < names.length; i++)
? ? ? ? ? ? {
? ? ? ? ? ? ? ? if (key == names[i])
? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? index = i;
? ? ? ? ? ? ? ? ? ? break;
? ? ? ? ? ? ? ? }
? ? ? ? ? ? }
? ? ? ? ? ? if (index == -1)
? ? ? ? ? ? {
? ? ? ? ? ? ? ? console.writeline("查無此人");
? ? ? ? ? ? }
? ? ? ? ? ? else
? ? ? ? ? ? {
? ? ? ? ? ? ? ? console.writeline("你要找的{0}在{1}位置", names[index], index + 1);
? ? ? ? ? ? }
2.反序 :當我說:“我愛你”這三個字的時候,你怎樣實現(xiàn)“你愛我”?
? ? ? ? ? ? String[] arr = { "我", "愛", "你" };
? ? ? ? ? ? for (int s = 0, e = arr.Length - 1; s < e; s++, e--)
? ? ? ? ? ? {
? ? ? ? ? ? ? ? string key = arr[s];
? ? ? ? ? ? ? ? arr[s] = arr[e];
? ? ? ? ? ? ? ? arr[e] = key;
? ? ? ? ? ? }
? ? ? ? ? ? for (int i = 0; i < arr.Length; i++)
? ? ? ? ? ? {
? ? ? ? ? ? ? ? Console.WriteLine(arr[i]);
? ? ? ? ? ? }
3.插入和刪除:這個很有意思了
插入數(shù)據(jù)
? ? ? ? ? ? int[] arr = { 1, 3, 4, 5, 6, 7, 87, 0, 0, 0, 0, 0, 0 };
? ? ? ? ? ? 插入位置
? ? ? ? ? ? int addIndex = 3;
? ? ? ? ? ? //插入數(shù)值
? ? ? ? ? ? int value = 20;
? ? ? ? ? ? // i? i+1
? ? ? ? ? ? for (int i = arr.Length - 2; i >= addIndex; i--)
? ? ? ? ? ? {
? ? ? ? ? ? ? ? arr[i + 1] = arr[i];
? ? ? ? ? ? }
? ? ? ? ? ? arr[addIndex] = value;
? ? ? ? ? ? for (int i = 0; i < arr.Length; i++)
? ? ? ? ? ? {
? ? ? ? ? ? ? ? Console.WriteLine(arr[i]);
? ? ? ? ? ? }
刪除數(shù)據(jù)
int delIndex = 4;
? ? ? ? ? ? arr[delIndex-1] = 0;
? ? ? ? ? ? for (int i = delIndex + 1; i < arr.Length; i++)
? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? i - 1,i
? ? ? ? ? ? ? ?? int x = arr[i];
? ? ? ? ? ? ? ?? arr[i] = arr[i - 1];
? ? ? ? ? ? ? ?? arr[i - 1] = x;
? ? ? ? ? ? }
? ? ? ? ? ? for (int i = 0; i < arr.Length; i++)
? ? ? ? ? ? {
? ? ? ? ? ? ? ? Console.WriteLine(arr[i]);
? ? ? ? ? ? }
以上就是我總結(jié)的數(shù)組的簡單使用,因為是第一次出文章,有什么問題我會在接下來的文章中修改,感謝大家的關(guān)注,下一篇我會寫關(guān)于C#方法的總結(jié)。