C#의 문자열 보간

이 자습서에서는 문자열 보간을 사용하여 결과 문자열에서 식 결과의 서식을 지정하고 포함하는 방법을 보여줍니다. 예제에서는 사용자가 기본 C# 개념 및 .NET 형식 서식 지정에 익숙하다고 가정합니다. 문자열 보간 또는 .NET 형식 서식 지정을 처음 접하는 경우 대화형 문자열 보간 자습서을 먼저 체크 아웃합니다. .NET의 형식 서식 지정에 대한 자세한 내용은 .NET의 서식 지정 형식을 참조하세요.

소개

문자열 리터럴을 보간된 문자열로 식별하려면 $ 기호를 사용하여 추가합니다. 보간된 문자열에서 값을 반환하는 유효한 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);
// Output:
// 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

이 예제에서 볼 수 있듯이 중괄호를 포함하여 보간된 문자열에 식을 포함합니다.

{<interpolationExpression>}

보간된 문자열은 문자열 복합 서식 지정 기능의 모든 기능을 지원합니다. 따라서 String.Format 메서드를 사용할 때 보다 읽기 쉬운 대안이 됩니다.

보간 식에 대한 서식 문자열을 지정하는 방법

식 결과의 형식에서 지원되는 형식 문자열을 지정하려면 콜론(":") 및 형식 문자열을 사용하여 보간 식을 따릅니다.

{<interpolationExpression>:<formatString>}

다음 예제에서는 날짜 및 시간 또는 숫자 결과를 생성하는 식의 표준 및 사용자 지정 서식 지정 문자열을 지정하는 방법을 보여줍니다.

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}.");
// Output:
// On Sunday, November 25, 1731 L. Euler introduced the letter e to denote 2.71828.

자세한 내용은 복합 서식 문서의 문자열 구성 요소 서식 섹션을 참조하세요.

필드 너비와 서식이 지정된 보간 식의 맞춤을 제어하는 방법

최소 필드 너비와 서식이 지정된 식 결과의 맞춤을 지정하려면 쉼표(",") 및 상수 식을 사용하여 보간 식을 따릅니다.

{<interpolationExpression>,<alignment>}

맞춤 값이 양수이면 서식이 지정된 식 결과는 오른쪽 맞춤입니다. 값이 음수이면 왼쪽 맞춤입니다.

맞춤 및 서식 문자열을 모두 지정해야 할 경우 맞춤 구성 요소를 시작합니다.

{<interpolationExpression>,<alignment>:<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}|");
// Output:
// Three classical Pythagorean means of 3 and 4:
// |Arithmetic|  3.500|
// |Geometric|  3.464|
// |Harmonic |  3.429|

출력 표시 예제에서 볼 수 있듯이 서식이 지정된 식 결과의 길이가 지정된 필드 너비를 초과하는 경우 맞춤 값은 무시됩니다.

자세한 내용은 복합 서식 문서의 맞춤 구성 요소 섹션을 참조하세요.

보간된 문자열에서 이스케이프 시퀀스를 사용하는 방법

보간된 문자열에서는 일반 문자열 리터럴을 사용할 수 있는 모든 이스케이프 시퀀스를 지원합니다. 자세한 내용은 문자열 이스케이프 시퀀스를 참조하세요.

이스케이프 시퀀스를 문자 그대로 해석하려면 약어 리터럴 문자열을 사용합니다. 보간된 축자 문자열은 둘 다 $@ 문자로 시작합니다. 어떤 순서로든 사용할 $@ 수 있습니다@$"...". 둘 다 $@"..." 유효한 보간된 축자 문자열입니다.

중괄호("{" 또는 "}")를 포함하려면 결과 문자열에서 2개의 중괄호("{{" 또는 "}}")를 사용합니다. 자세한 내용은 복합 서식 문서의 이스케이프 중괄호 섹션을 참조하세요.

다음 예제에서는 결과 문자열에 중괄호를 포함하고 약어 보간된 문자열을 만드는 방법을 보여줍니다.

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

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

C# 11부터 보간된 원시 문자열 리터럴을 사용할 수 있습니다.

보간 식에서 3개로 구성된 ?: 조건부 연산자를 사용하는 방법

보간 식에서 콜론(":")에 특별한 의미가 있으므로 식에서 조건부 연산자를 사용하기 위해 다음 예제에서 볼 수 있듯이 해당 식을 괄호로 묶습니다.

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

문자열 보간을 사용하여 문화권별 결과 문자열을 만드는 방법

기본적으로는 보간된 문자열은 모든 서식 지정 작업에 대해 CultureInfo.CurrentCulture 속성에서 정의한 현재 문화권을 사용합니다.

.NET 6부터 다음 예제와 같이 보간된 문자열을 문화권별 결과 문자열로 확인하는 데 이 메서드를 사용할 String.Create(IFormatProvider, DefaultInterpolatedStringHandler) 수 있습니다.

var cultures = new System.Globalization.CultureInfo[]
{
    System.Globalization.CultureInfo.GetCultureInfo("en-US"),
    System.Globalization.CultureInfo.GetCultureInfo("en-GB"),
    System.Globalization.CultureInfo.GetCultureInfo("nl-NL"),
    System.Globalization.CultureInfo.InvariantCulture
};
var date = DateTime.Now;
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       8/27/2023 12:35:31 PM      31,415,926.536
// en-GB         27/08/2023 12:35:31      31,415,926.536
// nl-NL         27-08-2023 12:35:31      31.415.926,536
//               08/27/2023 12:35:31      31,415,926.536

이전 버전의 .NET에서는 보간된 문자열을 인스턴스로 System.FormattableString 암시적으로 변환하고 해당 메서드를 ToString(IFormatProvider) 호출하여 문화권별 결과 문자열을 만듭니다. 다음 예제에서는 해당 작업을 수행하는 방법을 보여줍니다.

var cultures = new System.Globalization.CultureInfo[]
{
    System.Globalization.CultureInfo.GetCultureInfo("en-US"),
    System.Globalization.CultureInfo.GetCultureInfo("en-GB"),
    System.Globalization.CultureInfo.GetCultureInfo("nl-NL"),
    System.Globalization.CultureInfo.InvariantCulture
};
var date = DateTime.Now;
var number = 31_415_926.536;
FormattableString message = $"{date,23}{number,20:N3}";
foreach (var culture in cultures)
{
    var cultureSpecificMessage = message.ToString(culture);
    Console.WriteLine($"{culture.Name,-10}{cultureSpecificMessage}");
}
// Output is similar to:
// en-US       8/27/2023 12:35:31 PM      31,415,926.536
// en-GB         27/08/2023 12:35:31      31,415,926.536
// nl-NL         27-08-2023 12:35:31      31.415.926,536
//               08/27/2023 12:35:31      31,415,926.536

이 예제에서 볼 수 있듯이 하나의 FormattableString 인스턴스를 사용하여 다양한 문화권에 여러 결과 문자열을 생성할 수 있습니다.

고정 문화권을 사용하여 결과 문자열을 만드는 방법

.NET 6부터 다음 예제와 같이 보간된 문자열을 결과 문자열InvariantCulture로 확인하려면 이 메서드를 사용합니다String.Create(IFormatProvider, DefaultInterpolatedStringHandler).

string message = string.Create(CultureInfo.InvariantCulture, $"Date and time in invariant culture: {DateTime.Now}");
Console.WriteLine(message);
// Output is similar to:
// Date and time in invariant culture: 05/17/2018 15:46:24

이전 버전의 .NET에서는 메서드와 함께 다음 예제와 FormattableString.ToString(IFormatProvider) 같이 정적 FormattableString.Invariant 메서드를 사용할 수 있습니다.

string message = FormattableString.Invariant($"Date and time in invariant culture: {DateTime.Now}");
Console.WriteLine(message);
// Output is similar to:
// Date and time in invariant culture: 05/17/2018 15:46:24

결론

이 자습서에서는 문자열 보간 사용법의 일반적인 시나리오를 설명합니다. 문자열 보간에 대한 자세한 내용은 문자열 보간을 참조 하세요. .NET의 형식 서식 지정에 대한 자세한 내용은 .NET복합 서식 문서의 서식 지정 형식을 참조하세요.

참고 항목