Menu
CoddyTech

Metody tablic

Część sekcji Podstawy ścieżki C# w Coddy. Lekcja 59 z 70.

Tablice mają wiele metod (funkcji). Aby uzyskać dostęp do metody, napisz:

Array.MethodName(arrayName, otherParameters)

Popularne metody tablic:

Clear(array, index, length) — resetuje length elementów, zaczynając od index, do ich wartości domyślnej: 0 dla liczb, false dla bool, null dla string:

int[] numbers = {1, 2, 3, 4, 5};
Array.Clear(numbers, 1, 3);
// numbers będzie zawierać {1, 0, 0, 0, 5}

Reverse(array) — odwraca kolejność elementów w tablicy:

int[] numbers = {1, 2, 3, 4, 5};
Array.Reverse(numbers);
// numbers będzie zawierać {5, 4, 3, 2, 1}

Sort(array) — sortuje elementy tablicy w kolejności rosnącej:

int[] numbers = {5, 2, 9, 1, 5, 6};
Array.Sort(numbers);
// numbers będzie zawierać {1, 2, 5, 5, 6, 9}

Copy(sourceArray, sourceIndex, destinationArray, destinationIndex, length) – kopiuje length elementów z sourceArray, zaczynając od sourceIndex, do destinationArray, zaczynając od destinationIndex:

int[] source = {1, 2, 3, 4, 5};
int[] destination = new int[5];
Array.Copy(source, 0, destination, 0, source.Length);
// destination będzie zawierać {1, 2, 3, 4, 5}
challenge icon

Wyzwanie

Łatwy

Utwórz metodę o nazwie Merge, która przyjmuje dwie tablice jako argumenty. Metoda łączy te dwie tablice w jedną posortowaną tablicę i zwraca ją.

Na przykład następujące argumenty: Merge(new string[] {"1", "4", "2"}, new string[] {"2", "5", "9"}) zwrócą ["1", "2", "2", "4", "5", "9"]

Użyj Array.Copy(), aby skopiować elementy z jednej tablicy do drugiej. Składnia jest następująca: 

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

Na przykład:

// 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);

Tablica docelowa po skopiowaniu: 1 2 3 4 5

Spróbuj swoich sił

using System;


public class Program {
    public static string[] Merge(string[] arr1, string[] arr2) {
        string[] result = new string[arr1.Length + arr2.Length];
        // Skopiuj arr1 i arr2 do result

        // Następnie posortuj 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 iconSprawdź się

Ta lekcja zawiera krótki quiz. Zacznij lekcję, żeby na niego odpowiedzieć i śledzić swoje postępy.

Wszystkie lekcje w sekcji Podstawy

Poćwicz samodzielnie: Kompilator C# online