Menu
Coddy logo textTech

HashMap Methods

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

HashMap 메서드는 사전 데이터를 다루는 강력한 방법을 제공합니다. 몇 가지 일반적인 메서드를 살펴보겠습니다:

딕셔너리에 키가 존재하는지 확인합니다:

Dictionary<string, int> inventory = new Dictionary<string, int>();
inventory.Add("apples", 25);

bool hasApples = inventory.ContainsKey("apples");
// hasApples는 true가 됩니다

딕셔너리에서 모든 키(key)를 가져옵니다:

Dictionary<string, int> scores = new Dictionary<string, int>();
scores.Add("Alice", 95);
scores.Add("Bob", 87);

// 모든 키 가져오기
Dictionary<string, int>.KeyCollection keys = scores.Keys;
foreach (string name in keys)
{
    Console.WriteLine(name);
}

딕셔너리에서 모든 값을 가져옵니다:

// 모든 값 가져오기
Dictionary<string, int>.ValueCollection values = scores.Values;
foreach (int score in values)
{
    Console.WriteLine(score);
}

딕셔너리에서 항목을 제거합니다:

scores.Remove("Bob");
// 이제 딕셔너리에는 Alice의 점수만 포함됩니다

모든 항목 지우기:

scores.Clear();
// 이제 딕셔너리가 비어 있습니다

.Count를 사용하여 딕셔너리의 항목 수를 가져옵니다:

Dictionary<string, int> scores = new Dictionary<string, int>();
scores.Add("Alice", 95);
scores.Add("Bob", 87);

int total = scores.Count;
Console.WriteLine(total);
// 출력: 2
challenge icon

챌린지

중급

ProcessDictionary라는 이름의 메서드를 생성하세요. 이 메서드는 Dictionary<string, int>를 인수로 받아 다음 작업을 수행합니다:

  1. Keys:를 출력한 후 모든 키를 출력합니다 (한 줄에 하나씩)
  2. Values:를 출력한 후 모든 값을 출력합니다 (한 줄에 하나씩)
  3. 딕셔너리에 "total" 키가 포함되어 있는지 확인하고 Contains 'total': True 또는 Contains 'total': False를 출력합니다
  4. "temp" 키가 존재하면 제거합니다
  5. 이러한 작업 후 딕셔너리의 항목 수를 Count: 뒤에 출력합니다 (딕셔너리의 .Count 속성을 사용하세요)

직접 해보기

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

class Program
{
    static void ProcessDictionary(Dictionary<string, int> dict)
    {
        // 여기에 코드를 작성하세요
    }
    // 메인 코드는 무시하세요, 문자열을 `HashMap`으로 변환합니다
    static void Main(string[] args)
    {
        Dictionary<string, int> inputDict = 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)
                {
                    // 정규 표현식을 사용하여 키와 값을 추출합니다
                    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);
                        inputDict.Add(keyMatch, valueMatch);
                    }
                }
                
                ProcessDictionary(inputDict);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error parsing input: {ex.Message}");
            }
        }
        else
        {
            try
            {
                // Process traditional input format
                int n = int.Parse(firstLine);
                
                for (int i = 0; i < n; i++)
                {
                    string[] pair = Console.ReadLine().Split(':');
                    string key = pair[0];
                    int value = int.Parse(pair[1]);
                    inputDict.Add(key, value);
                }
                
                ProcessDictionary(inputDict);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error parsing input: {ex.Message}");
            }
        }
    }
}
quiz icon실력 점검

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

논리 및 흐름의 모든 레슨