요소 제거
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"]"Banana"를 찾아 제거했으므로 wasRemoved의 값은 true가 됩니다.
존재하지 않는 요소를 제거하려고 하면 다음과 같습니다.
bool wasRemoved = fruits.Remove("Orange");집합은 변경되지 않고, wasRemoved는 false가 됩니다.
챌린지
쉬움RemoveElement라는 이름의 메서드를 만들고 다음 두 인수를 받도록 하세요:
- 문자열의 HashSet(
set) - 제거할 문자열(
element)
메서드는 주어진 요소를 집합에서 제거하려고 시도해야 합니다. 요소가 성공적으로 제거되면 "Element removed: True"를 출력하고, 그렇지 않으면 "Element removed: 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);
// 정규식을 사용해 따옴표로 둘러싸인 모든 문자열을 찾습니다
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);
}
}이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
논리 및 흐름의 모든 레슨
직접 연습해 보세요: 온라인 C# 컴파일러