Menu
Coddy logo textTech

Metody tablic

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

Tablice mają wiele metod (funkcjonalności). Aby użyć metody, napisz:

Array.MethodName(arrayName, otherParameters)

Popularne metody tablic:

Clear(array, index, length) – czyści elementy tablicy, ustawiając zakres elementów na zero, false lub null:

int[] numbers = {1, 2, 3, 4, 5};
Array.Clear(numbers, 1, 3);
// numbers będzie mieć wartości {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 rosnąco:

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

Copy(sourceArray, sourceIndex, destinationArray, destinationIndex, length) – kopiuje zakres elementów z jednej tablicy do drugiej:

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

Przykład z różnymi pozycjami:

int[] source = {1, 2, 3, 4, 5};
int[] destination = new int[7];
Array.Copy(source, 1, destination, 2, 3);
// destination będzie mieć wartość {0, 0, 2, 3, 4, 0, 0}
// Skopiowano elementy 2, 3, 4 z source, zaczynając od indeksu 1
// Umieszczono je w destination, zaczynając od indeksu 2
challenge icon

Wyzwanie

Łatwy

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

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 wygląda następująco: 

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, 5);

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) {
        // Wpisz kod tutaj
    }

    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