Menu
CoddyTech

배열 복사

Coddy C# 여정의 기초 섹션에 포함된 레슨. 70개 중 58번째.

한 배열의 요소를 다른 배열로 복사하려면 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}이 됩니다
challenge icon

챌린지

쉬움

문자열 배열과 문자열 item을 받는 AddToEnd라는 메서드를 만드세요. 배열의 모든 요소를 같은 순서로 담고, 끝에 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));
    }
}
quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

기초의 모든 레슨

직접 연습해 보세요: 온라인 C# 컴파일러