C#에서의 문자열 보간

팁 (조언)

이 문서는 이미 하나 이상의 프로그래밍 언어를 알고 있으며 C#을 학습하는 개발자를 위한 기본 사항 섹션의 일부입니다. 프로그래밍을 처음 접하는 경우 먼저 시작 자습서로 시작 하세요.

다른 언어에서 오시겠습니까? C#의 문자열 보간은 JavaScript의 템플릿 리터럴(`${x}`) 또는 Python f 문자열(f"{x}")과 매우 유사합니다. 내부 {} 식은 유효한 C# 식일 수 있으며 문자열을 벗어나지 않고 서식 및 맞춤 지정자를 추가할 수 있습니다.

문자열 보간을 사용하면 리터럴 앞에 $를 붙여 문자열 리터럴 안에 식을 직접 포함할 수 있습니다.

double a = 3;
double b = 4;
Console.WriteLine($"Area of the right triangle with legs of {a} and {b} is {0.5 * a * b}");
Console.WriteLine($"Length of the hypotenuse of the right triangle with legs of {a} and {b} is {CalculateHypotenuse(a, b)}");
double CalculateHypotenuse(double leg1, double leg2) => Math.Sqrt(leg1 * leg1 + leg2 * leg2);
// => Area of the right triangle with legs of 3 and 4 is 6
// => Length of the hypotenuse of the right triangle with legs of 3 and 4 is 5

각각 { }보간 식입니다. C#은 식을 평가하고, 메서드를 호출 ToString() 하여 결과를 문자열로 변환하고, 텍스트를 결과로 대체합니다. null 식에 대한 문자열 보간은 빈 문자열입니다. 대부분의 경우 기본 변환은 원하는 출력을 생성하므로 더 이상 수행할 필요가 없습니다.

보간된 문자열은 String.Format보다 가독성이 더 높은 대안이며, 복합 서식의 전체 기능을 지원합니다. 기존의 위치 지정 형식 문자열로 할 수 있는 모든 작업(형식 지정자, 정렬, 문화권을 고려한 서식 지정, 상수 문자열)은 보간된 문자열로도 할 수 있습니다. 이 문서의 나머지 부분에는 이러한 옵션이 설명됩니다. 결과를 보다 세부적으로 제어해야 하는 경우에만 도달합니다. 그렇지 않으면 일반 $"{expression}" 형식으로 충분합니다.

구문 및 기본 처리기 형식의 언어 참조 처리는 보간된 문자열 참조를 참조하세요. 보간 및 사용자 지정 보간된 문자열 처리기와 같은 Span<char> 성능 중심 항목은 문자열 작업을 참조하세요.

서식 문자열 적용

식 결과의 서식을 지정하는 방법을 제어하려면 콜론 및 표준 또는 사용자 지정 형식 문자열을 사용하여 식을 따릅니다.

{<expression>:<formatString>}

다음 예제에서는 DateTime 값과 Double 값의 형식을 지정합니다:

var date = new DateTime(1731, 11, 25);
Console.WriteLine($"On {date:dddd, MMMM dd, yyyy} L. Euler introduced the letter e to denote {Math.E:F5}.");
// => On Sunday, November 25, 1731 L. Euler introduced the letter e to denote 2.71828.

필드 너비와 정렬 설정

정렬된 출력을 생성하려면 쉼표와 최소 필드 너비를 사용하여 식을 따릅니다. 양수 너비는 값을 오른쪽 정렬하고, 음수 너비는 왼쪽 정렬합니다:

{<expression>,<width>}
var titles = new Dictionary<string, string>()
{
    ["Doyle, Arthur Conan"] = "Hound of the Baskervilles, The",
    ["London, Jack"] = "Call of the Wild, The",
    ["Shakespeare, William"] = "Tempest, The"
};

Console.WriteLine("Author and Title List");
Console.WriteLine();
Console.WriteLine($"|{"Author",-25}|{"Title",30}|");
foreach (var title in titles)
{
    Console.WriteLine($"|{title.Key,-25}|{title.Value,30}|");
}
// => Author and Title List
// =>
// => |Author                   |                         Title|
// => |Doyle, Arthur Conan      |Hound of the Baskervilles, The|
// => |London, Jack             |         Call of the Wild, The|
// => |Shakespeare, William     |                  Tempest, The|

맞춤 및 서식 문자열이 모두 필요한 경우 맞춤을 먼저 배치합니다.

{<expression>,<width>:<formatString>}
const int NameAlignment = -9;
const int ValueAlignment = 7;
double a = 3;
double b = 4;
Console.WriteLine($"Three classical Pythagorean means of {a} and {b}:");
Console.WriteLine($"|{"Arithmetic",NameAlignment}|{0.5 * (a + b),ValueAlignment:F3}|");
Console.WriteLine($"|{"Geometric",NameAlignment}|{Math.Sqrt(a * b),ValueAlignment:F3}|");
Console.WriteLine($"|{"Harmonic",NameAlignment}|{2 / (1 / a + 1 / b),ValueAlignment:F3}|");
// => Three classical Pythagorean means of 3 and 4:
// => |Arithmetic|  3.500|
// => |Geometric|  3.464|
// => |Harmonic |  3.429|

서식이 지정된 값이 요청된 너비보다 긴 경우 C#은 너비를 무시하고 전체 값을 내보냅니다.

중괄호를 이스케이프하고 이스케이프 시퀀스를 사용합니다

보간된 문자열은 일반 문자열 리터럴과 동일한 이스케이프 시퀀스를 지원합니다. 결과에 리터럴 { 또는 } 문자를 포함하려면 해당 문자를 두 번 입력하세요({{ 또는 }}).

백슬라시를 포함하는 경로 및 기타 문자열의 경우 이전 축자 형식()보다 보간된 원시 문자열 리터럴($"""..."""$@"...")을 선호합니다. 원시 문자열 리터럴은 이스케이프 시퀀스를 처리하지 않으므로 백슬래시는 있는 그대로 표시됩니다:

int[] xs = [1, 2, 7, 9];
int[] ys = [7, 9, 12];
Console.WriteLine($"Find the intersection of the {{{string.Join(", ", xs)}}} and {{{string.Join(", ", ys)}}} sets.");
// => Find the intersection of the {1, 2, 7, 9} and {7, 9, 12} sets.

var userName = "Jane";
var stringWithEscapes = $"C:\\Users\\{userName}\\Documents";
var rawInterpolated = $"""C:\Users\{userName}\Documents""";
Console.WriteLine(stringWithEscapes);
Console.WriteLine(rawInterpolated);
// => C:\Users\Jane\Documents
// => C:\Users\Jane\Documents

조건식 사용

콜론은 보간 식 내에서 특별한 의미를 가지므로 조건부 exoressuin을 괄호로 래핑합니다.

var rand = new Random(42);
for (int i = 0; i < 3; i++)
{
    Console.WriteLine($"Coin flip: {(rand.NextDouble() < 0.5 ? "heads" : "tails")}");
}

수식을 여러 줄에 걸쳐 표시합니다.

가독성을 높이기 위해 긴 보간 식을 여러 줄에서 중단합니다. 여러 줄에 걸친 문자열 보간 식은 C# 11부터 사용할 수 있습니다. 다음 예제에서는 보간된 식을 리터럴 텍스트와 구분하기 위해 { 문자와 } 문자 사이에 줄 바꿈을 추가합니다.

int[] numbers = [3, 1, 4, 1, 5, 9, 2, 6];
Console.WriteLine($"Total: {
        numbers.Sum()
        }, average: {numbers.Average():F2}.");
// => Total: 31, average: 3.88.

상수 문자열 빌드

보간된 모든 식이 상수 값인 경우 보간된 상수 문자열을 작성할 수 있습니다. 따라서 컴파일 시간 상수가 필요한 특성 인수, switch 패턴 및 기타 컨텍스트에 사용할 수 있습니다.

const string Audience = "world";
const string Greeting = $"Hello, {Audience}!";
Console.WriteLine(Greeting);
// => Hello, world!

특정 문화권을 사용하여 서식 지정

기본적으로 보간된 문자열은 날짜, 숫자 및 통화 표시 형식에 영향을 주는 CultureInfo.CurrentCulture를 사용하여 값의 형식을 지정합니다. 결정적인 출력을 위해 String.Create(IFormatProvider, DefaultInterpolatedStringHandler)에 명시적인 문화권 정보를 전달하세요.

CultureInfo[] cultures =
[
    CultureInfo.GetCultureInfo("en-US"),
    CultureInfo.GetCultureInfo("en-GB"),
    CultureInfo.GetCultureInfo("nl-NL"),
    CultureInfo.InvariantCulture
];
var date = new DateTime(2026, 5, 21, 12, 35, 31);
var number = 31_415_926.536;
foreach (var culture in cultures)
{
    var cultureSpecificMessage = string.Create(culture, $"{date,23}{number,20:N3}");
    Console.WriteLine($"{culture.Name,-10}{cultureSpecificMessage}");
}
// Output is similar to:
// => en-US       5/21/2026 12:35:31 PM      31,415,926.536
// => en-GB         21/05/2026 12:35:31      31,415,926.536
// => nl-NL         21-05-2026 12:35:31      31.415.926,536
// =>               05/21/2026 12:35:31      31,415,926.536

고정 출력(로그, 파일 형식, 컴퓨터에서 읽을 수 있는 데이터)의 경우 다음을 전달 CultureInfo.InvariantCulture합니다.

var timestamp = new DateTime(2026, 5, 21, 15, 46, 24);
string message = string.Create(CultureInfo.InvariantCulture, $"Date and time in invariant culture: {timestamp}");
Console.WriteLine(message);
// => Date and time in invariant culture: 05/21/2026 15:46:24

참고하십시오