Menu
Coddy logo textTech

Check If Key Exists

Parte da seção Lógica & Fluxo do Journey de C# da Coddy — lição 48 de 66.

Para verificar se uma chave existe em um HashMap (Dictionary em C#), você pode usar o método ContainsKey().

Primeiro, crie um Dictionary:

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

Adicione alguns pares chave-valor:

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

Agora verifique se uma chave existe:

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

Após executar o código acima, a variável exists será true.

Você pode usar isso em uma instrução condicional:

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

Desafio

Fácil

Crie um método chamado CheckKeyExists que recebe dois argumentos:

  • Um Dictionary<string, int> (dicionário)
  • Uma string (chave) para verificar

O método deve verificar se a chave existe no dicionário e imprimir:

  • "Key exists" se a chave for encontrada
  • "Key does not exist" se a chave não for encontrada

Folha de consulta

Para verificar se uma chave existe em um Dictionary, use o método ContainsKey():

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

bool exists = ages.ContainsKey("John"); // retorna true

Utilize em instruções condicionais:

if (ages.ContainsKey("John"))
{
    Console.WriteLine("John's age is in the dictionary");
}
else
{
    Console.WriteLine("John's age is not in the dictionary");
}

Experimente você mesmo

using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
class Program
{
    public static void CheckKeyExists(Dictionary<string, int> dictionary, string key)
    {
        // Escreva o código aqui
    }
    
    static void Main(string[] args)
    {
        Dictionary<string, int> inventory = new Dictionary<string, int>();
        
        // Lendo a entrada do inventário - aceita tanto o formato JSON quanto o formato linha por linha
        string firstLine = Console.ReadLine();
        
        // Verifica se a entrada está no formato JSON
        if (firstLine != null && firstLine.StartsWith("{") && firstLine.EndsWith("}"))
        {
            try
            {
                // Processa a entrada JSON
                string jsonContent = firstLine.Substring(1, firstLine.Length - 2);
                
                // Divide por vírgulas que não estão dentro de aspas
                string pattern = @",(?=(?:[^""]*""[^""]*"")*[^""]*$)";
                string[] entries = Regex.Split(jsonContent, pattern);
                
                foreach (string entry in entries)
                {
                    // Extrai a chave e o valor usando 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 iconTeste seus conhecimentos

Esta lição inclui um quiz rápido. Comece a lição para respondê-lo e acompanhar seu progresso.

Todas as lições de Lógica & Fluxo