Computer >> 컴퓨터 >  >> 프로그래밍 >> C#

C# Stack.ToString() 메서드 완벽 가이드 – 예제 코드와 실행 결과

C#의 Stack.ToString() 메서드는 Stack 클래스 객체의 문자열 표현(string representation)을 얻는 데 사용됩니다. 모든 클래스가 기본적으로 상속받는 Object 클래스의 ToString()을 활용하는 것으로, 스택에 저장된 각 요소를 화면에 출력하거나 문자열 형태로 다룰 때 유용하게 쓰입니다.

구문

이 메서드의 기본 구문은 다음과 같습니다.

public string ToString ();

매개변수를 받지 않으며, 해당 객체를 나타내는 문자열을 반환합니다.

예제 1 – 정수 요소를 가진 스택

먼저 정수형 데이터를 Push()로 추가한 뒤, foreach 문과 ToString() 메서드로 각 요소를 출력하는 예제를 살펴보겠습니다.

using System;
using System.Collections;
public class Demo {
    public static void Main() {
        Stack stack = new Stack();
        stack.Push(150);
        stack.Push(300);
        stack.Push(500);
        stack.Push(750);
        stack.Push(1000);
        stack.Push(1250);
        stack.Push(1500);
        stack.Push(2000);
        stack.Push(2500);
        Console.WriteLine("Stack elements...");
        foreach(int val in stack) {
            Console.WriteLine(val.ToString());
        }
        Console.WriteLine("Count of elements = "+stack.Count);
        stack.Push(3000);
        stack.Push(3500);
        stack.Push(4000);
        Console.WriteLine("\nStack elements...updated");
        foreach(int val in stack) {
            Console.WriteLine(val.ToString());
        }
        Console.WriteLine("\nCount of elements (updated) = "+stack.Count);
        Console.WriteLine("\nCopying the Stack to a new array...");
        Object[] objArr = stack.ToArray();
        foreach(Object ob in objArr) {
            Console.WriteLine(ob);
        }
        Console.WriteLine("\nCount of elements in array = "+objArr.Length);
    }
}

실행 결과

위 코드를 실행하면 다음과 같은 결과가 출력됩니다.

Stack elements...
2500
2000
1500
1250
1000
750
500
300
150
Count of elements = 9

Stack elements...updated
4000
3500
3000
2500
2000
1500
1250
1000
750
500
300
150
Count of elements (updated) = 12

Copying the Stack to a new array...
4000
3500
3000
2500
2000
1500
1250
1000
750
500
300
150

Count of elements in array = 12

출력 결과를 보면 마지막에 Push된 요소가 가장 먼저 출력되는데, 이는 스택이 LIFO(Last-In-First-Out, 후입선출) 구조로 동작하기 때문입니다. 또한 ToArray() 메서드를 사용하면 스택의 모든 요소를 배열로 손쉽게 복사할 수 있습니다.

예제 2 – 문자열 요소를 가진 스택

이번에는 문자열 데이터를 저장한 스택에서 ToString(), Peek(), Clear() 메서드를 함께 활용하는 예제를 살펴보겠습니다.

using System;
using System.Collections;
public class Demo {
    public static void Main() {
        Stack stack = new Stack();
        stack.Push("Inspiron");
        stack.Push("Alienware");
        stack.Push("Projectors");
        stack.Push("Monitors");
        stack.Push("XPS");
        stack.Push("Laptop");
        stack.Push("Notebook");
        Console.WriteLine("Stack elements...");
        foreach(string val in stack) {
            Console.WriteLine(val.ToString());
        }
        Console.WriteLine("Count of elements = "+stack.Count);
        Console.WriteLine("Element at the top = "+ stack.Peek());
        stack.Push("Ultrabook");
        stack.Push("Cameras");
        stack.Push("Keyboards");
        Console.WriteLine("\nStack elements...updated");
        foreach(string val in stack) {
            Console.WriteLine(val.ToString());
        }
        Console.WriteLine("Element at the top = "+ stack.Peek());
        Console.WriteLine("\nCount of elements (updated) = "+stack.Count);
        stack.Clear();
        Console.Write("Count of elements (updated) = "+stack.Count);
    }
}

실행 결과

위 코드를 실행하면 다음과 같은 결과가 출력됩니다.

Stack elements...
Notebook
Laptop
XPS
Monitors
Projectors
Alienware
Inspiron
Count of elements = 7
Element at the top = Notebook
Stack elements...updated
Keyboards
Cameras
Ultrabook
Notebook
Laptop
XPS
Monitors
Projectors
Alienware
Inspiron
Element at the top = Keyboards
Count of elements (updated) = 10
Count of elements (updated) = 0

핵심 정리

  • ToString(): 객체의 문자열 표현을 반환하여 요소를 출력할 때 활용됩니다.
  • Peek(): 스택에서 요소를 제거하지 않고 맨 위(top) 요소만 확인합니다.
  • Clear(): 스택의 모든 요소를 제거하여 Count가 0이 됩니다.
  • ToArray(): 스택의 요소들을 새로운 배열에 순서대로 복사합니다.

이처럼 Stack.ToString() 메서드는 스택 내부의 데이터를 문자열로 변환해 출력하거나 로깅할 때 유용하며, Peek(), Clear(), ToArray() 등의 메서드와 함께 사용하면 스택을 더욱 효율적으로 관리할 수 있습니다.