Removing an Element
Coddy C# 여정의 논리 및 흐름 섹션에 포함된 레슨 — 66개 중 58번째.
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");세트는 변경되지 않고, wasRemoved는 false가 될 것입니다.
챌린지
쉬움RemoveElement이라는 이름의 메서드를 만들고 두 개의 인수를 받도록 하세요:
- 문자열의 HashSet (
set) - 제거할 문자열 (
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>();
// JSON 형식인지 확인하기 위해 첫 번째 줄 읽기
string firstLine = Console.ReadLine();
string elementToRemove;
// 입력이 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());
}
}
// 제거할 요소를 위해 두 번째 줄 읽기
string secondLine = Console.ReadLine();
// 요소가 JSON 문자열 형식인지 확인
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
{
// 전통 입력 형식 처리
string[] elements = firstLine.Split(',');
foreach (string element in elements)
{
set.Add(element.Trim());
}
// 전통 형식으로 제거할 요소 읽기
elementToRemove = Console.ReadLine();
}
RemoveElement(set, elementToRemove);
}
}이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
논리 및 흐름의 모든 레슨
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