Menu
Coddy logo textTech

Checking if an Element Exists

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

Contains(element) メソッドは、HashSet に特定の要素が存在するかどうかを確認します。要素が見つかった場合は true を、それ以外の場合は false を返します。

空の HashSet を作成します:

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

HashSet にいくつかの要素を追加します:

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

要素が存在するかどうかを確認:

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

結果を条件文で使用できます:

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

チャレンジ

簡単

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

  • 文字列の HashSet (set)
  • チェックする文字列 (element)

このメソッドは、要素がセットに存在するかどうかをチェックし、文字列メッセージを返却してください:

  • 要素が存在する場合、"The element 'X' exists in the set" を返却
  • 要素が存在しない場合、"The element 'X' does not exist in the set" を返却

'X' はチェックされている実際の要素の値です。

チートシート

Contains(element) メソッドは、HashSet に特定の要素が存在するかどうかを確認します。要素が見つかった場合は true を返し、そうでなければ false を返します。

空の HashSet を作成:

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

HashSet に要素を追加:

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

要素の存在を確認:

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

条件分岐文で使用:

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

自分で試してみよう

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

public class Program
{
    public static string ElementExists(HashSet<string> set, string element)
    {
        // ここにコードを書いてください
        return "";
    }
    
    public static void Main()
    {
        // JSON形式かどうかを確認するために最初の行を読み取る
        string firstLine = Console.ReadLine();
        string elementToCheck = Console.ReadLine();
        HashSet<string> set = new HashSet<string>();
        
        // 入力がJSON配列形式かどうかを確認
        if (firstLine != null && firstLine.StartsWith("[") && firstLine.EndsWith("]"))
        {
            try
            {
                // 角括弧の間の内容を抽出
                string arrayContent = firstLine.Substring(1, firstLine.Length - 2);
                
                // 正規表現を使用してすべての引用符付き文字列をマッチ
                MatchCollection matches = Regex.Matches(arrayContent, @"""([^""]*)""");
                
                foreach (Match match in matches)
                {
                    // キャプチャされたグループ(引用符なし)を追加
                    if (match.Groups.Count > 1)
                    {
                        set.Add(match.Groups[1].Value.Trim());
                    }
                }
                
                // 要素が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
        {
            // 従来のカンマ区切りの入力を処理
            string[] elements = firstLine.Split(',');
            foreach (string element in elements)
            {
                set.Add(element.Trim());
            }
        }
        
        string result = ElementExists(set, elementToCheck);
        Console.WriteLine(result);
    }
}
quiz icon腕試し

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

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