Menu
Coddy logo textTech

Checking if an Element Exists

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

O método Contains(element) verifica se um elemento específico existe no HashSet. Ele retorna true se o elemento for encontrado, e false caso contrário.

Crie um HashSet vazio:

HashSet<string> fruits = new HashSet<string>();

Adicione alguns elementos ao HashSet:

fruits.Add("Apple");
fruits.Add("Banana");

Verificar se um elemento existe:

bool hasApple = fruits.Contains("Apple");  // Returns true
bool hasOrange = fruits.Contains("Orange"); // Returns false

Você pode usar o resultado em instruções condicionais:

if (fruits.Contains("Apple"))
{
    Console.WriteLine("Apple is in the set");
}
challenge icon

Desafio

Fácil

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

  • Um HashSet de strings (set)
  • Uma string (element) para verificar

O método deve verificar se o elemento existe no conjunto e retornar uma mensagem de string:

  • Se o elemento existir, retorne "The element 'X' exists in the set"
  • Se o elemento não existir, retorne "The element 'X' does not exist in the set"

Onde 'X' é o valor real do elemento sendo verificado.

Folha de consulta

O método Contains(element) verifica se um elemento específico existe no HashSet. Ele retorna true se o elemento for encontrado, e false caso contrário.

Crie um HashSet vazio:

HashSet<string> fruits = new HashSet<string>();

Adicione elementos ao HashSet:

fruits.Add("Apple");
fruits.Add("Banana");

Verifique se um elemento existe:

bool hasApple = fruits.Contains("Apple");  // Returns true
bool hasOrange = fruits.Contains("Orange"); // Returns false

Use em instruções condicionais:

if (fruits.Contains("Apple"))
{
    Console.WriteLine("Apple is in the set");
}

Experimente você mesmo

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

public class Program
{
    public static string ElementExists(HashSet<string> set, string element)
    {
        // Escreva seu código aqui
        return "";
    }
    
    public static void Main()
    {
        // Lê a primeira linha para verificar se está no formato JSON
        string firstLine = Console.ReadLine();
        string elementToCheck = Console.ReadLine();
        HashSet<string> set = new HashSet<string>();
        
        // Verifica se a entrada está no formato de array JSON
        if (firstLine != null && firstLine.StartsWith("[") && firstLine.EndsWith("]"))
        {
            try
            {
                // Extrai o conteúdo entre colchetes
                string arrayContent = firstLine.Substring(1, firstLine.Length - 2);
                
                // Usa regex para combinar todas as strings entre aspas
                MatchCollection matches = Regex.Matches(arrayContent, @"""([^""]*)""");
                
                foreach (Match match in matches)
                {
                    // Adiciona o grupo capturado (sem aspas)
                    if (match.Groups.Count > 1)
                    {
                        set.Add(match.Groups[1].Value.Trim());
                    }
                }
                
                // Verifica se o elemento está no formato de string JSON
                Match elementMatch = Regex.Match(elementToCheck, @"""([^""]*)""");
                if (elementMatch.Success && elementMatch.Groups.Count > 1)
                {
                    elementToCheck = elementMatch.Groups[1].Value;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error parsing JSON input: {ex.Message}");
                return;
            }
        }
        else
        {
            // Processa a entrada tradicional separada por vírgulas
            string[] elements = firstLine.Split(',');
            foreach (string element in elements)
            {
                set.Add(element.Trim());
            }
        }
        
        string result = ElementExists(set, elementToCheck);
        Console.WriteLine(result);
    }
}
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