Menu
Coddy logo textTech

Checking if an Element Exists

Parte de la sección Lógica y Flujo del Journey de C# de Coddy — lección 59 de 66.

El método Contains(element) verifica si un elemento específico existe en el HashSet. Devuelve true si el elemento se encuentra, y false en caso contrario.

Crear un HashSet vacío:

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

Agrega algunos elementos al HashSet:

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

Comprobar si un elemento existe:

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

Puedes usar el resultado en sentencias condicionales:

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

Desafío

Fácil

Crea un método llamado ElementExists que toma dos argumentos:

  • Un HashSet de cadenas (set)
  • Una cadena (element) para verificar

El método debe verificar si el elemento existe en el conjunto y devolver un mensaje de cadena:

  • Si el elemento existe, devolver "The element 'X' exists in the set"
  • Si el elemento no existe, devolver "The element 'X' does not exist in the set"

Donde 'X' es el valor real del elemento que se está verificando.

Hoja de referencia

El método Contains(element) verifica si un elemento específico existe en el HashSet. Devuelve true si se encuentra el elemento, y false en caso contrario.

Crear un HashSet vacío:

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

Agregar elementos al HashSet:

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

Verificar si existe un elemento:

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

Usar en sentencias condicionales:

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

Pruébalo tú mismo

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

public class Program
{
    public static string ElementExists(HashSet<string> set, string element)
    {
        // Escribe tu código aquí
        return "";
    }
    
    public static void Main()
    {
        // Lee la primera línea para verificar si es formato JSON
        string firstLine = Console.ReadLine();
        string elementToCheck = Console.ReadLine();
        HashSet<string> set = new HashSet<string>();
        
        // Verifica si la entrada está en formato de array JSON
        if (firstLine != null && firstLine.StartsWith("[") && firstLine.EndsWith("]"))
        {
            try
            {
                // Extrae el contenido entre corchetes cuadrados
                string arrayContent = firstLine.Substring(1, firstLine.Length - 2);
                
                // Usa regex para hacer coincidir todas las cadenas entre comillas
                MatchCollection matches = Regex.Matches(arrayContent, @"""([^""]*)""");
                
                foreach (Match match in matches)
                {
                    // Agrega el grupo capturado (sin comillas)
                    if (match.Groups.Count > 1)
                    {
                        set.Add(match.Groups[1].Value.Trim());
                    }
                }
                
                // Verifica si el elemento está en formato de cadena 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
        {
            // Procesa la entrada tradicional separada por comas
            string[] elements = firstLine.Split(',');
            foreach (string element in elements)
            {
                set.Add(element.Trim());
            }
        }
        
        string result = ElementExists(set, elementToCheck);
        Console.WriteLine(result);
    }
}
quiz iconPonte a prueba

Esta lección incluye un breve cuestionario. Empieza la lección para responderlo y registrar tu progreso.

Todas las lecciones de Lógica y Flujo