Menu
CoddyTech

배열 메서드

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

배열에는 다양한 메서드(기능)가 있습니다. 메서드에 접근하려면 다음과 같이 작성하세요:

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) - sourceIndex에서 시작하는 sourceArray의 요소 length개를 destinationIndex에서 시작하는 destinationArray에 복사합니다:

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# 컴파일러