Menu
Coddy logo textTech

Verificare se un elemento esiste

Fa parte della sezione Logica e flusso del percorso C# di Coddy. Lezione 59 di 66.

Il metodo Contains(element) verifica se un elemento specifico è presente in HashSet. Restituisce true se l’elemento viene trovato e false altrimenti.

Crea un HashSet vuoto:

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

Aggiungi alcuni elementi all'HashSet:

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

Verifica se un elemento esiste:

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

Puoi usare il risultato nelle istruzioni condizionali:

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

Sfida

Facile

Crea un metodo chiamato ElementExists che accetta due argomenti:

  • Un HashSet di stringhe (set)
  • Una stringa (element) da controllare

Il metodo deve verificare se l'elemento esiste nel set e restituire un messaggio sotto forma di stringa:

  • Se l'elemento esiste, restituisci "The element 'X' exists in the set"
  • Se l'elemento non esiste, restituisci "The element 'X' does not exist in the set"

Dove 'X' è il valore effettivo dell'elemento da controllare.

Provalo tu

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

public class Program
{
    public static string ElementExists(HashSet<string> set, string element)
    {
        // Scrivi il tuo codice qui
        return "";
    }
    
    public static void Main()
    {
        // Leggi la prima riga per verificare se è in formato JSON
        string firstLine = Console.ReadLine();
        string elementToCheck = Console.ReadLine();
        HashSet<string> set = new HashSet<string>();
        
        // Verifica se l'input è nel formato di un array JSON
        if (firstLine != null && firstLine.StartsWith("[") && firstLine.EndsWith("]"))
        {
            try
            {
                // Estrai il contenuto tra le parentesi quadre
                string arrayContent = firstLine.Substring(1, firstLine.Length - 2);
                
                // Usa una regex per trovare tutte le stringhe tra virgolette
                MatchCollection matches = Regex.Matches(arrayContent, @"""([^""]*)""");
                
                foreach (Match match in matches)
                {
                    // Aggiungi il gruppo catturato (senza virgolette)
                    if (match.Groups.Count > 1)
                    {
                        set.Add(match.Groups[1].Value.Trim());
                    }
                }
                
                // Verifica se l'elemento è nel formato di una stringa 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
        {
            // Elabora l'input tradizionale separato da virgole
            string[] elements = firstLine.Split(',');
            foreach (string element in elements)
            {
                set.Add(element.Trim());
            }
        }
        
        string result = ElementExists(set, elementToCheck);
        Console.WriteLine(result);
    }
}
quiz iconMettiti alla prova

Questa lezione include un breve quiz. Inizia la lezione per rispondere e tenere traccia dei tuoi progressi.

Tutte le lezioni di Logica e flusso

Esercitati da solo: Compilatore C# online