Menu
Coddy logo textTech

Removing an Element

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

El método Remove(element) elimina el elemento especificado del HashSet, si existe. Este método devuelve true si el elemento se eliminó correctamente, y false si el elemento no se encontró en el conjunto.

Crear un HashSet vacío:

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

Agrega algunos elementos al conjunto:

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

Después de ejecutar el código anterior, el conjunto fruits contiene:

["Apple", "Banana", "Cherry"]

Ahora, elimina "Banana" del conjunto:

bool wasRemoved = fruits.Remove("Banana");

Después de eliminar, el conjunto contiene:

["Apple", "Cherry"]

El valor de wasRemoved será true porque "Banana" fue encontrado y eliminado.

Si intentamos eliminar un elemento que no existe:

bool wasRemoved = fruits.Remove("Orange");

El conjunto permanece sin cambios, y wasRemoved será false.

challenge icon

Desafío

Fácil

Crea un método llamado RemoveElement que tome dos argumentos:

  1. Un HashSet de cadenas (set)
  2. Una cadena (element) para eliminar

El método debe intentar eliminar el elemento dado del conjunto. Si el elemento fue eliminado exitosamente, imprime "Element removed: True", de lo contrario imprime "Element removed: False". Luego, imprime el conjunto actualizado en una nueva línea.

Hoja de referencia

El método Remove(element) elimina el elemento especificado del HashSet y devuelve true si tiene éxito, false si el elemento no se encontró:

HashSet<string> fruits = new HashSet<string>();
fruits.Add("Apple");
fruits.Add("Banana");
fruits.Add("Cherry");

bool wasRemoved = fruits.Remove("Banana"); // devuelve true
bool notFound = fruits.Remove("Orange");   // devuelve false

Pruébalo tú mismo

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

public class Program
{
    public static void RemoveElement(HashSet<string> set, string element)
    {
        // Escribe tu código aquí
    }
    
    public static void Main()
    {
        HashSet<string> set = new HashSet<string>();
        
        // Read first line to check if it's JSON format
        string firstLine = Console.ReadLine();
        string elementToRemove;
        
        // Check if input is in JSON array format
        if (firstLine != null && firstLine.StartsWith("[") && firstLine.EndsWith("]"))
        {
            try
            {
                // Extract content between square brackets
                string arrayContent = firstLine.Substring(1, firstLine.Length - 2);
                
                // Use regex to match all quoted strings
                MatchCollection matches = Regex.Matches(arrayContent, @"""([^""]*)""");
                
                foreach (Match match in matches)
                {
                    // Add the captured group (without quotes)
                    if (match.Groups.Count > 1)
                    {
                        set.Add(match.Groups[1].Value.Trim());
                    }
                }
                
                // Read second line for element to remove
                string secondLine = Console.ReadLine();
                
                // Check if element is in JSON string format
                Match elementMatch = Regex.Match(secondLine, @"""([^""]*)""");
                if (elementMatch.Success && elementMatch.Groups.Count > 1)
                {
                    elementToRemove = elementMatch.Groups[1].Value;
                }
                else
                {
                    elementToRemove = secondLine;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error parsing JSON input: {ex.Message}");
                return;
            }
        }
        else
        {
            // Process traditional input format
            string[] elements = firstLine.Split(',');
            foreach (string element in elements)
            {
                set.Add(element.Trim());
            }
            
            // Read element to remove in traditional format
            elementToRemove = Console.ReadLine();
        }
        
        RemoveElement(set, elementToRemove);
    }
}
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