复制数组
本课属于 Coddy C# 学习旅程的“基础知识”单元。第 58 课,共 70 课。
要将元素从一个数组复制到另一个数组,请使用 Array.Copy。它需要五个参数:
Array.Copy(source, sourceIndex, destination, destinationIndex, length);它从 source 中取出 length 个元素,从 sourceIndex 开始,并将它们写入 destination,从 destinationIndex 开始。目标数组必须已存在,并且容量足够。
最后一个参数是数量:要复制多少个元素,而不是复制到哪里停止。
int[] scores = {90, 75, 60, 85};
int[] firstTwo = new int[2];
Array.Copy(scores, 0, firstTwo, 0, 2);
// firstTwo 的值将是 {90, 75}destinationIndex 是第一个被复制元素放置的位置。使用 source.Length 作为数量,无论数组大小如何,都会复制整个数组:
int[] source = {1, 2, 3};
int[] destination = new int[6];
Array.Copy(source, 0, destination, 3, source.Length);
// destination 将是 {0, 0, 0, 1, 2, 3}要将一个数组接在另一个数组后面,请把第二个数组复制到第一个数组结束的位置。这个位置就是第一个数组的 Length:
int[] first = {1, 2};
int[] second = {7, 8, 9};
int[] all = new int[first.Length + second.Length];
Array.Copy(first, 0, all, 0, first.Length);
Array.Copy(second, 0, all, first.Length, second.Length);
// all 的值将是 {1, 2, 7, 8, 9}当两个数组都从索引 0 开始时,可以使用更简短的写法:Array.Copy(source, destination, length):
int[] source = {4, 5, 6, 7};
int[] destination = new int[3];
Array.Copy(source, destination, 3);
// destination 将是 {4, 5, 6}挑战
简单创建一个名为 AddToEnd 的方法,它接收一个字符串数组和一个字符串 item。它会返回一个新数组,其中包含原数组的所有元素,顺序不变,并在末尾添加 item。
例如,AddToEnd(new string[] {"a", "b", "c"}, "d") 会返回 ["a", "b", "c", "d"]。
使用 Array.Copy() 将元素复制到新数组中。
输入格式(2 行):
- 第 1 行:用逗号分隔的数组元素(例如
a,b,c) - 第 2 行:要添加的元素(例如
d)
输出格式:新数组中的元素以逗号和空格分隔(例如 a, b, c, d)
亲手试试
using System;
public class Program {
public static string[] AddToEnd(string[] arr, string item) {
// 在这里编写代码
}
public static void Main(string[] args) {
string[] arr = Console.ReadLine().Split(',');
string item = Console.ReadLine();
string[] result = AddToEnd(arr, item);
Console.WriteLine(string.Join(", ", result));
}
}这节课包含一个小测验。开始学习即可作答,并记录你的进度。
基础知识中的所有课
自己练习: C# 在线编译器