Menu
Coddy logo textTech

Accessing Values

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

C#에서는 HashMap의 대응으로 Dictionary<TKey, TValue>를 사용합니다. Dictionary에 항목을 추가한 후에는 이를 검색해야 합니다.

문자열 키와 int 값으로 Dictionary를 생성하세요:

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

일부 항목을 추가:

studentScores.Add("John", 95);
studentScores.Add("Mary", 88);

키를 사용하여 값에 접근하기:

int johnScore = studentScores["John"];

위의 코드를 실행한 후, johnScore에는 다음이 포함됩니다:

95

주의하세요! 존재하지 않는 키에 접근하려고 하면 KeyNotFoundException이 발생합니다:

// "Bob"이 딕셔너리에 없으면 예외가 발생합니다
int bobScore = studentScores["Bob"];
challenge icon

챌린지

쉬움

GetValueByKey이라는 이름의 메서드를 생성하세요. 이 메서드는 두 개의 인수를 받습니다:

  1. Dictionary<string, int> (사전).
  2. 조회할 문자열 (key).

이 메서드는 주어진 키에 대한 값을 접근하려고 시도해야 하며:

  • 키가 존재하면, 값을 출력합니다.
  • 키가 존재하지 않으면, "Key not found"를 출력합니다.

치트 시트

string 키와 int 값으로 Dictionary 생성:

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

Dictionary에 항목 추가:

studentScores.Add("John", 95);
studentScores.Add("Mary", 88);

키를 사용하여 값 접근:

int johnScore = studentScores["John"];

존재하지 않는 키에 접근하면 KeyNotFoundException이 발생합니다:

// "Bob"이 딕셔너리에 없으면 예외가 발생합니다
int bobScore = studentScores["Bob"];

직접 해보기

using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

class Program
{
    public static void GetValueByKey(Dictionary<string, int> dictionary, string key)
    {
        // 여기에 코드를 작성하세요
    }
    
    static void Main(string[] args)
    {
        // JSON 형식의 딕셔너리를 읽어옵니다: {"key1":value1,"key2":value2}
        string dictionaryInput = Console.ReadLine();
        string key = Console.ReadLine();
        
        Dictionary<string, int> dictionary = new Dictionary<string, int>();
        
        // 입력 문자열을 파싱하여 딕셔너리를 생성합니다
        if (!string.IsNullOrEmpty(dictionaryInput))
        {
            try
            {
                // 입력이 JSON 형식인지 확인합니다
                if (dictionaryInput.StartsWith("{") && dictionaryInput.EndsWith("}"))
                {
                    // 중괄호를 제거합니다
                    string jsonContent = dictionaryInput.Substring(1, dictionaryInput.Length - 2);
                    
                    // 따옴표 안에 있지 않은 쉼표를 기준으로 분할합니다
                    string pattern = @",(?=(?:[^""]*""[^""]*"")*[^""]*$)";
                    string[] entries = Regex.Split(jsonContent, pattern);
                    
                    foreach (string entry in entries)
                    {
                        // 정규 표현식을 사용하여 키와 값을 추출합니다
                        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);
                            dictionary.Add(keyMatch, valueMatch);
                        }
                    }
                }
                // Handle the original format "key1:value1,key2:value2" as fallback
                else
                {
                    string[] pairs = dictionaryInput.Split(',');
                    foreach (string pair in pairs)
                    {
                        string[] keyValue = pair.Split(':');
                        if (keyValue.Length == 2)
                        {
                            dictionary.Add(keyValue[0], int.Parse(keyValue[1]));
                        }
                    }
                }
                
                GetValueByKey(dictionary, key);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error parsing input: {ex.Message}");
            }
        }
    }
}
quiz icon실력 점검

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

논리 및 흐름의 모든 레슨