Menu
Coddy logo textTech

בדיקה אם מפתח קיים

חלק מהיחידה לוגיקה וזרימת תוכנית במסלול ה-C# של Coddy. שיעור 48 מתוך 66.

כדי לבדוק אם מפתח קיים ב-HashMap (מילון ב-C#), אפשר להשתמש בשיטה ContainsKey().

ראשית, צרו מילון:

Dictionary<string, int> ages = new Dictionary<string, int>();

הוסף כמה זוגות מפתח-ערך:

ages.Add("John", 25);
ages.Add("Mary", 30);

כעת בדוק אם קיים מפתח:

bool exists = ages.ContainsKey("John");

לאחר ביצוע הקוד שלמעלה, המשתנה exists יהיה true.

אפשר להשתמש בזה במשפט תנאי:

if (ages.ContainsKey("John"))
{
    Console.WriteLine("John's age is in the dictionary");
}
else
{
    Console.WriteLine("John's age is not in the dictionary");
}
challenge icon

אתגר

קל

צרו מתודה בשם CheckKeyExists שמקבלת שני ארגומנטים:

  • Dictionary<string, int> (מילון)
  • מחרוזת (מפתח) לבדיקה

המתודה צריכה לבדוק אם המפתח קיים במילון ולהדפיס:

  • "Key exists" אם המפתח נמצא
  • "Key does not exist" אם המפתח לא נמצא

נסו בעצמכם

using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
class Program
{
    public static void CheckKeyExists(Dictionary<string, int> dictionary, string key)
    {
        // כתבו כאן קוד
    }
    
    static void Main(string[] args)
    {
        Dictionary<string, int> inventory = new Dictionary<string, int>();
        
        // קריאת קלט המלאי - מקבלת גם פורמט JSON וגם פורמט של שורה אחר שורה
        string firstLine = Console.ReadLine();
        
        // בדקו אם הקלט הוא בפורמט JSON
        if (firstLine != null && firstLine.StartsWith("{") && firstLine.EndsWith("}"))
        {
            try
            {
                // עבדו את קלט ה-JSON
                string jsonContent = firstLine.Substring(1, firstLine.Length - 2);
                
                // פצלו לפי פסיקים שאינם בתוך מירכאות
                string pattern = @",(?=(?:[^""]*""[^""]*"")*[^""]*$)";
                string[] entries = Regex.Split(jsonContent, pattern);
                
                foreach (string entry in entries)
                {
                    // חלצו מפתח וערך באמצעות regex
                    Match match = Regex.Match(entry, @"""([^""]+)""\s*:\s*(\d+)");
                    if (match.Success)
                    {
                        string keyMatch = match.Groups[1].Value;
                        int valueMatch = int.Parse(match.Groups[2].Value);
                        inventory.Add(keyMatch, valueMatch);
                    }
                }
                
                // Reading the key to check directly
                string keyToCheck = Console.ReadLine();
                CheckKeyExists(inventory, keyToCheck);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error parsing input: {ex.Message}");
            }
        }
        else
        {
            // Process original line-by-line format
            string line = firstLine;
            
            // Read lines until an empty line is entered
            while (!string.IsNullOrEmpty(line))
            {
                try
                {
                    string[] parts = line.Split(':');
                    if (parts.Length == 2)
                    {
                        inventory.Add(parts[0], int.Parse(parts[1]));
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Error parsing line: {ex.Message}");
                }
                
                // Read next line
                line = Console.ReadLine();
            }
            
            // Reading the key to check
            string keyToCheck = Console.ReadLine();
            CheckKeyExists(inventory, keyToCheck);
        }
    }
}
quiz iconבחנו את עצמכם

השיעור הזה כולל חידון קצר. התחילו את השיעור כדי לענות עליו ולעקוב אחרי ההתקדמות.

כל השיעורים ביחידה לוגיקה וזרימת תוכנית

תרגלו בעצמכם: קומפיילר C# אונליין