Menu
CoddyTech

数组方法

本课属于 Coddy C# 学习旅程的“基础知识”单元。第 59 课,共 70 课。

数组包含许多方法(功能)。要调用方法,请写:

Array.MethodName(arrayName, otherParameters)

常用数组方法:

Clear(array, index, length):将从 index 开始的 length 个元素重置为默认值:数字为 0,bool 为 false,string 为 null:

int[] numbers = {1, 2, 3, 4, 5};
Array.Clear(numbers, 1, 3);
// numbers 将变为 {1, 0, 0, 0, 5}

Reverse(array):反转数组中元素的顺序:

int[] numbers = {1, 2, 3, 4, 5};
Array.Reverse(numbers);
// numbers 将变为 {5, 4, 3, 2, 1}

Sort(array):按升序排列数组中的元素:

int[] numbers = {5, 2, 9, 1, 5, 6};
Array.Sort(numbers);
// numbers 将变为 {1, 2, 5, 5, 6, 9}

Copy(sourceArray, sourceIndex, destinationArray, destinationIndex, length):从 sourceArray 中的 sourceIndex 位置开始,将 length 个元素复制到 destinationArray 中,从 destinationIndex 位置开始:

int[] source = {1, 2, 3, 4, 5};
int[] destination = new int[5];
Array.Copy(source, 0, destination, 0, source.Length);
// destination 将变为 {1, 2, 3, 4, 5}
challenge icon

挑战

简单

创建一个名为 Merge 的方法,接收两个数组作为参数。该方法将两个数组合并为一个排序后的数组并返回。

例如,以下参数:Merge(new string[] {"1", "4", "2"}, new string[] {"2", "5", "9"}) 将返回 ["1", "2", "2", "4", "5", "9"]

使用 Array.Copy() 将元素从一个数组复制到另一个数组。语法如下: 

Array.Copy(sourceArray, sourceStartPosition, destinationArray, destinationStartPosition, length)

例如:

// Source array
string[] sourceArray = {"1", "2", "3", "4", "5"};

// Destination array
string[] destinationArray = new string[5];

// Copy elements from sourceArray to destinationArray
Array.Copy(sourceArray, 0, destinationArray, 0, sourceArray.Length);

复制后的目标数组:1 2 3 4 5

亲手试试

using System;


public class Program {
    public static string[] Merge(string[] arr1, string[] arr2) {
        string[] result = new string[arr1.Length + arr2.Length];
        // 将 arr1 和 arr2 复制到 result 中

        // 然后对 result 排序
        return result;
    }

    public static void Main(string[] args) {
        string textArr1 = Console.ReadLine();
        string textArr2 = Console.ReadLine();
        string[] arr1 = textArr1.Split(",");
        string[] arr2 = textArr2.Split(",");

        string[] mergedArray = Merge(arr1, arr2);
        Console.WriteLine(string.Join(", ", mergedArray));
    }
}
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

基础知识中的所有课

自己练习: C# 在线编译器