Menu
CoddyTech

HashMap 메서드

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

HashMap 메서드는 딕셔너리 데이터로 작업할 수 있는 강력한 방법을 제공합니다. 몇 가지 일반적인 메서드를 살펴보겠습니다:

딕셔너리에 키가 있는지 확인합니다:

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

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

딕셔너리에서 모든 키 가져오기:

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");
// 이제 Dictionary에는 Alice의 점수만 있습니다

Remove()는 키가 존재하고 제거된 경우 true를 반환하고, 그렇지 않은 경우 false를 반환합니다. 존재하지 않는 키를 제거해도 오류가 발생하지 않습니다.

모든 항목 지우기:

scores.Clear();
// Dictionary가 이제 비어 있습니다

.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

챌린지

중급

Dictionary<string, int>를 인수로 받아 다음 작업을 수행하는 ProcessDictionary라는 메서드를 만드세요:

  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)
    {
        // 여기에 코드를 작성하세요
    }
    // main 코드는 무시하세요. string을 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)
                {
                    // 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);
                        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실력 점검

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

논리 및 흐름의 모든 레슨

직접 연습해 보세요: 온라인 C# 컴파일러