본문 바로가기
Program Language/C#

Part1. C# 첫발 내딛기(22. 문자열 연결)

by 토담이아빠 2023. 1. 15.

 

C#에서 문자열을 연결하는 방법에는 4가지가 있습니다. 이번 포스팅은 이 방법들에 대해서 정리했습니다.


 

첫 번째 방법 : '+' 연산자 사용

 

가장 직관적인 방법입니다. '+"연산자를 사용하여 문자열 및 문자열 변수를 이어줍니다. 다음 예제를 통해 사용법을 확인할 수 있습니다.


using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace StringConcat
{
    internal class Program
    {
        static void Main(string[] args)
        {
            string userName = "Steve";
            string dateString = "Jan 1, 2023";
            string str = "Hello " + userName + ". Today is " + dateString;
            str += ".";

            Console.WriteLine(str);

        }
    }
}

결과

Hello Steve. Today is Jan 1, 2023.

두 번째 방법 : 문자열 보간(string interpolation)

 

C# 6 이후에 추가된 기능으로 $ 문자를 사용하면 문자열 안에서 변수값을 표현할 수 있어서 읽기 쉬우며 사용법이 편리합니다. 변수는 문자열 안 { }로 표시합니다.


using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace StringConcat
{
    internal class Program
    {
        static void Main(string[] args)
        {
            string userName = "bikang";
            string date = DateTime.Today.ToShortDateString();

            string str = $"Hello {userName}. Today is {date}.";
            Console.WriteLine(str);

        }
    }
}

결과

Hello bikang. Today is 2023-01-15.

세 번째 방법 : String.Format

 

예전 포스팅에서 이미 설명한 방법으로 문자열 안 변수는 {0}. {1}. {2}, ... 와 같이 순차적인 인덱스로 표현가능합니다.


using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace StringConcat
{
    internal class Program
    {
        static void Main(string[] args)
        {
            decimal temp = 20.4m;
            string str = String.Format("At {0}, the temperature is {1}℃.", DateTime.Now, 20.4);
            Console.WriteLine(str);
        }
    }
}

결과

At 2023-01-15 오후 10:57:41, the temperature is 20.4℃.

네 번째 방법 : String.Concat()과 String.Join()

 

Concat()이나 Join() 메서드는 문자열 배열이나 리스트 등의 컬렉션을 연결할 때 사용합니다. Join() 메서드는 구분 기호도 표시할 수 있습니다.


using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace StringConcat
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(String.Concat("I ", "am ", "a ", "boy"));

            string[] animals = { "mouse", "cow", "tiger", "rabbit", "snake" };
            string str = String.Concat(animals);
            Console.WriteLine(str);

            str = String.Join(", ", animals);
            Console.WriteLine(str);
        }
    }
}

결과

I am a boy
mousecowtigerrabbitsnake
mouse, cow, tiger, rabbit, snake

[Review]

"초보자를 위한 C# 200제(2판)" 저자 / 강병익

댓글