首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

Visual Studio 給 Java 開發者的 C# 指南 (15) - 多維陣列初始化、巢狀迴圈、Array.Sort/Reverse 靜態方法

     編輯:關於C語言

多維陣列宣告與初始化 (三種寫法)

int[,] arr1 = { {1,2,3}, {4,5,6} };
int[,] arr2 = new int[2,3] { {1,2,3}, {4,5,6} };
int[,] arr3 = new int[,] { {1,2,3}, {4,5,6} };

巢狀迴圈初始化

int[,] arr = new int[5,4];
foreach (int i in arr)          // 注意:foreach 取得的是元素值,無法直接賦值
{
    // 正確寫法需用 for 迴圈索引
    for (int r = 0; r < arr.GetLength(0); r++)
        for (int c = 0; c < arr.GetLength(1); c++)
            arr[r,c] = 0;
}

原文 foreach 寫法有誤,此處修正為索引賦值。

System.Array 靜態方法

陣列實為 System.Array 實例,提供實用靜態方法:

  • Array.Reverse(arr):反轉元素順序。
  • Array.Sort(arr):排序 (需元素實作 IComparable)。

完整示範程式

using System;
public class ArrayMethods
{
    static void Main()
    {
        string[] names = new string[5];
        Console.WriteLine("Enter five employee names:");
        for (int i=0;i<5;i++) names[i] = Console.ReadLine();

        Console.WriteLine("\n** Original **");
        foreach (string n in names) Console.Write(n + " ");

        Array.Reverse(names);
        Console.WriteLine("\n\n** Reversed **");
        foreach (string n in names) Console.Write(n + " ");

        Array.Sort(names);
        Console.WriteLine("\n\n** Sorted **");
        foreach (string n in names) Console.Write(n + " ");
    }
}

範例輸出

Enter five employee names:
Luca
Angie
Brian
Kent
Beatriz
** Original **
Luca Angie Brian Kent Beatriz
** Reversed **
Beatriz Kent Brian Angie Luca
** Sorted **
Angie Beatriz Brian Kent Luca
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved