Menu
Coddy logo textTech

Removing an Element

CoddyのC#ジャーニー「ロジックとフロー」セクションの一部 — レッスン 58/66。

Remove(element) メソッドは、存在する場合、指定された要素を HashSet から削除します。このメソッドは、要素が正常に削除された場合に true を返し、セットに要素が見つからない場合に false を返します。

空の HashSet を作成:

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

セットにいくつかの要素を追加します:

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

上記のコードを実行した後、セット fruits には以下のものが含まれています:

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

今、セットから「Banana」を削除します:

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

削除後、セットには次のものが含まれます:

["Apple", "Cherry"]

wasRemoved の値は true になります。なぜなら、"Banana" が見つかって削除されたからです。

存在しない要素を削除しようとすると:

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

セットは変更されず、wasRemovedfalse になります。

challenge icon

チャレンジ

簡単

RemoveElement という名前のメソッドを作成し、2つの引数を受け取るようにしてください:

  1. 文字列の HashSet (set)
  2. 削除する文字列 (element)

このメソッドは、指定された要素をセットから削除しようと試みます。要素が正常に削除された場合、"Element removed: True" を出力し、そうでない場合は "Element removed: False" を出力します。その後、新しい行に更新されたセットを出力します。

チートシート

Remove(element) メソッドは、HashSet から指定された要素を削除し、成功した場合に true を、要素が見つからなかった場合に false を返します:

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

bool wasRemoved = fruits.Remove("Banana"); // true を返します
bool notFound = fruits.Remove("Orange");   // false を返します

自分で試してみよう

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

public class Program
{
    public static void RemoveElement(HashSet<string> set, string element)
    {
        // ここにコードを記述してください
    }
    
    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 icon腕試し

このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。

ロジックとフローのすべてのレッスン