값에 접근하기
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"];챌린지
쉬움GetValueByKey라는 이름의 메서드를 만들고 다음 두 인수를 받도록 하세요.
- Dictionary<string, int>(딕셔너리).
- 조회할 string(키).
메서드는 지정된 키의 값에 접근하려고 시도하며 다음과 같이 동작해야 합니다.
- 키가 있으면 값을 출력합니다.
- 키가 없으면 "Key not found"를 출력합니다.
직접 해보기
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 형식의 dictionary를 읽어 들입니다: {"key1":value1,"key2":value2}
string dictionaryInput = Console.ReadLine();
string key = Console.ReadLine();
Dictionary<string, int> dictionary = new Dictionary<string, int>();
// 입력 문자열을 파싱하여 dictionary를 생성합니다
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)
{
// 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);
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}");
}
}
}
}이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
논리 및 흐름의 모든 레슨
직접 연습해 보세요: 온라인 C# 컴파일러