Menu
Coddy logo textTech

מתודות של מערכים

חלק מהיחידה יסודות במסלול ה-C# של Coddy. שיעור 58 מתוך 69.

מערכים כוללים שיטות רבות (פונקציונליות). כדי לגשת לשיטה, כתבו:

Array.MethodName(arrayName, otherParameters)

שיטות נפוצות של מערכים:

Clear(array, index, length) - מנקה את האיברים במערך, ומגדירה טווח של איברים לאפס, false או 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) - מעתיקה טווח של איברים ממערך אחד לאחר:

int[] source = {1, 2, 3, 4, 5};
int[] destination = new int[5];
Array.Copy(source, 0, destination, 0, 5);
// destination יהיה {1, 2, 3, 4, 5}

דוגמה עם מיקומים שונים:

int[] source = {1, 2, 3, 4, 5};
int[] destination = new int[7];
Array.Copy(source, 1, destination, 2, 3);
// destination יהיה {0, 0, 2, 3, 4, 0, 0}
// הועתקו האיברים 2, 3, 4 מתוך source החל מאינדקס 1
// הם הוצבו ב-destination החל מאינדקס 2
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, 5);

המערך היעד לאחר ההעתקה: 1 2 3 4 5

נסו בעצמכם

using System;


public class Program {
    public static string[] Merge(string[] arr1, string[] arr2) {
        // כתבו כאן קוד
    }

    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# אונליין