[C#] 정리 : 배열

Young·2024년 5월 29일
0

C#

목록 보기
8/9

int[] scores = new int[5];

new를 통해서 메모리가 할당되며 scores 배열의 주소값은 scores[0]의 주소값과 동일하다. 위 코드는 정수로 이루어진 scores라는 배열을 만들 건데 그 배열 안에 들어있는 원소가 5개라는 뜻이다. 0번지부터 시작해서 5개라 인덱스는 5에서 하나가 작은 4까지 있다.


  • 선언과 동시에 초기화하기
string[] 배열명 = new string[3] {”가”, “나”, “다”};
// 용량 헷갈리면 오류 뜬다

string[] 배열명 = new string[] {”가”, “나”, “다”};
// 비워도 괜찮다

string[] 배열명 = {”가”, “나”, “다”};
// new 없이 바로 넣어도 된다.
  • 배열과 같이 쓰는 친구들
배열명.Length(); 		// 배열의 용량
배열명.Sort();			// 오름차순 정렬
배열명.Indexof();		// 특정 데이터 인덱스 반환
배열명.FindIndex();	// 지정한 조건 데이터 찾기
배열명.Clear();		// 배열 초기화


2차원 배열 [행, 열]

튜플이나 딕셔너리로 대체하는 게 훨씬 효율적이다.


컬렉션 : 용량이 정해지지 않았고 가변적인 배열

ArratList()


배열을 뱉어낼 때

using System;
using System.Collections;

namespace thisIsCSharp
{
    class MainApp
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Queue는 선입선출");
            Queue que = new Queue ();
            que.Enqueue("가");
            que.Enqueue("나");
            que.Enqueue("다");
            que.Enqueue("라");
            que.Enqueue("마");       // .Enqueue  값을 넣고 넣고 넣고

            while (que.Count > 0)
            {
                Console.Write($"{que.Dequeue()} ");   // .Dequeue 앞에서부터 빼
            }

            Console.WriteLine();
            Console.WriteLine();

            Console.WriteLine("Stack은 선입후출");
            Stack stack = new Stack ();
            stack.Push("A");
            stack.Push("B");
            stack.Push("C");    
            stack.Push("D");
            stack.Push("E");                // .Push 값을 밀어 넣고 

            while (stack.Count > 0)
            {
                Console.Write($"{stack.Pop()} ");   // .Pop 뒤에 넣은 것부터 뽑!는다
            }

            Console.WriteLine();
            Console.WriteLine();

            Console.WriteLine("Hashtable은 키와 값");
            Hashtable ht = new Hashtable ();
            ht["하나"] = "One";
            ht["Two"] = 2;
            ht[3] = "셋";
            ht[2] = 4;

            Console.WriteLine(ht["하나"]);
            Console.WriteLine(ht["Two"]);
            Console.WriteLine(ht[3]);
            Console.WriteLine(ht[2]);               // 해당하는 값 그대로 출력
        }
    }
} 

profile
Beginner : C#

0개의 댓글