Copying Arrays
Part of the Fundamentals section of Coddy's C# journey. Lesson 58 of 70.
To copy elements from one array into another, use Array.Copy. It takes five arguments:
Array.Copy(source, sourceIndex, destination, destinationIndex, length);It takes length elements from source, starting at sourceIndex, and writes them into destination, starting at destinationIndex. The destination array must already exist and be big enough.
The last argument is a count: how many elements to copy, not where to stop.
int[] scores = {90, 75, 60, 85};
int[] firstTwo = new int[2];
Array.Copy(scores, 0, firstTwo, 0, 2);
// firstTwo will be {90, 75}destinationIndex is where the first copied element lands. Using source.Length as the count copies the whole array, whatever its size:
int[] source = {1, 2, 3};
int[] destination = new int[6];
Array.Copy(source, 0, destination, 3, source.Length);
// destination will be {0, 0, 0, 1, 2, 3}To put one array after another, copy the second one to the position where the first one ends. That position is the first array's 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 will be {1, 2, 7, 8, 9}When both arrays start at index 0, there is a shorter form, Array.Copy(source, destination, length):
int[] source = {4, 5, 6, 7};
int[] destination = new int[3];
Array.Copy(source, destination, 3);
// destination will be {4, 5, 6}Challenge
EasyCreate a method named AddToEnd that receives an array of strings and a string item. It returns a new array that holds every element of the array, in the same order, with item added at the end.
For example, AddToEnd(new string[] {"a", "b", "c"}, "d") returns ["a", "b", "c", "d"].
Use Array.Copy() to copy the elements into the new array.
Input format (2 lines):
- Line 1: the array elements separated by commas (e.g.
a,b,c) - Line 2: the item to add (e.g.
d)
Output format: the new array's elements separated by a comma and a space (e.g. a, b, c, d)
Try it yourself
using System;
public class Program {
public static string[] AddToEnd(string[] arr, string item) {
// Write code here
}
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));
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorIncrement/DecrementPost Increment/DecrementArithmetic Shortcuts5Operators Part 2
Comparison OperatorsLogical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 311Arrays Basics
Declaring ArraysAccessing ElementsModifying ArraysCopying ArraysArray MethodsRecap - Product ArrayEdit Recap - Reversed ArrayPractice on your own: Online C# compiler