Menu
Coddy logo textTech

Check If Key Exists

Coddy C# 여정의 논리 및 흐름 섹션에 포함된 레슨 — 66개 중 48번째.

HashMap(C#의 Dictionary)에서 키가 존재하는지 확인하려면 ContainsKey() 메서드를 사용할 수 있습니다.

먼저, Dictionary를 생성하세요:

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

몇 가지 키-값 쌍을 추가하세요:

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

이제 키가 존재하는지 확인하세요:

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

위의 코드를 실행한 후, 변수 existstrue가 됩니다.

이를 조건문에서 사용할 수 있습니다:

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> (dictionary)
  • 확인할 string (key)

이 메서드는 딕셔너리에서 키가 존재하는지 확인하고 다음을 출력해야 합니다:

  • 키가 발견되면 "Key exists"
  • 키가 발견되지 않으면 "Key does not exist"

치트 시트

Dictionary에서 키가 존재하는지 확인하려면 ContainsKey() 메서드를 사용하세요:

Dictionary<string, int> ages = new Dictionary<string, int>();
ages.Add("John", 25);
ages.Add("Mary", 30);

bool exists = ages.ContainsKey("John"); // returns 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");
}

직접 해보기

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실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

논리 및 흐름의 모든 레슨