Checking if an Element Exists
Coddy C# 여정의 논리 및 흐름 섹션에 포함된 레슨 — 66개 중 59번째.
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");
}챌린지
쉬움ElementExists라는 이름을 가진 메서드를 생성하세요. 두 개의 인수를 받습니다:
- 문자열의 HashSet (
set) - 확인할 문자열 (
element)
이 메서드는 set에 요소가 존재하는지 확인하고 문자열 메시지를 반환해야 합니다:
- 요소가 존재하면 "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);
// 모든 인용된 문자열을 매치하기 위해 regex 사용
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);
}
}이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
논리 및 흐름의 모든 레슨
1Multi-dimensional Arrays
2D Arrays BasicsDeclaring and Initializing 2DAccessing 2D Array ElementsNested Loops with 2D ArraysJagged ArraysCommon Matrix OperationsRecap - Multi-dimensional4Flow Control Techniques
Early ReturnsGuard ClausesJump Statements (goto)Break and ContinueFlatten Nested Conditionals7Logical Operators Advanced
Short-Circuit EvaluationConditional Logical OperatorsOperator PrecedenceRecap - Advanced Operators2Advanced Decision Making
Multiple ConditionsComplex Boolean LogicIf vs. Switch ComparisonNested Switch StatementsRecap - Advanced Decisions5Exception Handling
Try-Catch BasicsException TypesMultiple Catch BlocksWorking with FilesFinally BlockUsing vs. Try-FinallyCustom ExceptionsRecap - Error Handling8Data Analysis System
Data Collection SetupData Entry Logic11HashSet Part 1
What is a HashSet?Adding an ElementRemoving an ElementChecking if an Element ExistsEmpty and SizeRecap - HashSet3Loop Enhancements
Loop PerformanceIterating ComplexEach Loop TypeRefactoring LoopsRecap - Optimized Loops6Null Handling
Null Reference BasicsNullable Value TypesNull Checking PatternsDefensive ProgrammingRecap - Null Safety