Menu
CoddyTech

检查元素是否存在

本课属于 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");  // 返回 true
bool hasOrange = fruits.Contains("Orange"); // 返回 false

你可以在条件语句中使用结果:

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

挑战

简单

创建一个名为 ElementExists 的方法,它接受两个参数:

  • 一个字符串的 HashSet(set)
  • 一个要检查的字符串(element)

该方法应检查元素是否存在于集合中,并返回一条字符串消息:

  • 如果元素存在,返回 "The element 'X' exists in the set"
  • 如果元素不存在,返回 "The element 'X' does not exist in the set"

其中 'X' 是要检查的实际元素值。

亲手试试

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());
                    }
                }
                
                // 检查 element 是否为 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自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

逻辑与流程中的所有课

自己练习: C# 在线编译器