Menu
CoddyTech

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

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

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

Array.MethodName(arrayName, otherParameters)

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

Clear(array, index, length) - מאפסת length איברים, החל מ־index, לערך ברירת המחדל שלהם: 0 עבור מספרים, false עבור bool, null עבור string:

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) - מעתיקה length איברים מתוך sourceArray, החל ב-sourceIndex, אל תוך destinationArray, החל ב-destinationIndex:

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