Menu
Coddy logo textTech

Empty and Size

Coddy C# 여정의 논리 및 흐름 섹션에 포함된 레슨 — 66개 중 60번째.

HashSet은 비어 있는지 확인하고 크기를 확인하는 메서드를 제공합니다.

빈 HashSet 생성

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

Count를 사용하여 HashSet이 비어 있는지 확인

bool isEmpty = colors.Count == 0;
// isEmpty is true

HashSet에 몇 가지 요소를 추가하세요

colors.Add("Red");
colors.Add("Blue");
colors.Add("Green");

HashSet의 크기 가져오기

int size = colors.Count;
// size is 3

Any() 메서드를 사용하여 HashSet이 비어 있는지 확인할 수도 있습니다.

bool hasElements = colors.Any();
// hasElements는 세트에 요소가 포함되어 있으므로 true입니다.
challenge icon

챌린지

쉬움

CountAndCheck이라는 메서드를 생성하세요. 이 메서드는 문자열의 HashSet을 인수로 받습니다. 메서드는 다음을 수행해야 합니다:

  1. HashSet이 비어 있는지 확인하세요.
  2. 비어 있으면 "Empty set"을 출력하세요.
  3. 그렇지 않으면 HashSet의 요소 수인 {count}를 사용하여 "Set contains {count} elements"를 출력하세요.

치트 시트

HashSet이 비어 있는지 Count를 사용하여 확인:

bool isEmpty = colors.Count == 0;

HashSet의 크기 가져오기:

int size = colors.Count;

HashSet에 요소가 있는지 Any()를 사용하여 확인:

bool hasElements = colors.Any();

직접 해보기

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    public static void CountAndCheck(HashSet<string> set)
    {
        // 여기에 코드를 작성하세요
    }
    
    static void Main(string[] args)
    {
        // 쉼표로 구분된 HashSet 요소들의 입력을 읽습니다
        // 입력이 비어 있으면 빈 HashSet을 생성합니다
        string input = Console.ReadLine();
        
        HashSet<string> set = new HashSet<string>();
        if (!string.IsNullOrEmpty(input))
        {
            string[] elements = input.Split(',');
            foreach (string element in elements)
            {
                set.Add(element.Trim());
            }
        }
        
        CountAndCheck(set);
    }
}
quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

논리 및 흐름의 모든 레슨