본문 바로가기
이건 알아야지's/C#

C#- 문자열 보간

by 하루디 2023. 6. 27.

📌 $@이란?

문자열 보간

C# 6.0에서 새로 도입된 기능으로 더 간결하게 문자열의 양식을 맞출 수 있도록 도와준다.

 

보간 문자열

(String interpolation)

$ 특수문자는 리터럴을 보간된 문자로 식별하는데,

보간된 문자열이란 보간식이 포함될 수 있는 문자열 리터럴이다.

 

축자 문자열

(Verbatim string)

@ 특수 문자는 축자 식별자로 사용된다.

문자열 리터럴이 축자로 해석될 것임을 나타낸다.

 

 

📌사용법

$ :

기본 string.Format( )과 기능은 동일하지만 더 간편하게 출력서식을 지정할 수 있다.

{ } 보간식이 포함된 문자열 “ ” 앞에 $를 붙여서 사용한다.

  • 중괄호{{ }}에 둘러싸인 표현식은 단일 중괄호 문자를 생성한다.
int X = 2;
int Y = 3;

var pointMessage = $"""The point "{X}, {Y}" is {Math.Sqrt(X * X + Y * Y)} from the origin""";

// output:  The point "2, 3" is 3.605551275463989 from the origin.

 

@ :

  • 역슬래시 \\는 escape 문자로 취급하지 않는다.
  • string filename1 = @"c:\\documents\\files\\u0066.txt"; string filename2 = "c:\\\\documents\\\\files\\\\u0066.txt"; Console.WriteLine(filename1); Console.WriteLine(filename2); // The example displays the following output: // c:\\documents\\files\\u0066.txt // c:\\documents\\files\\u0066.txt
  • 인용부호 “”는 그대로 해석되지 않고 큰따옴표 1개로 생성된다
  • string s1 = "He said, \\"This is the last \\u0063hance\\x0021\\""; string s2 = @"He said, ""This is the last \\u0063hance\\x0021"""; Console.WriteLine(s1); Console.WriteLine(s2); // The example displays the following output: // He said, "This is the last chance!" // He said, "This is the last \\u0063hance\\x0021"
  • @식별자를 사용해서 for루프에서 사용되는 for라는 이름의 식별자를 정의할 수 있다
  • string[] @for = { "John", "James", "Joan", "Jamie" }; for (int ctr = 0; ctr < @for.Length; ctr++) { Console.WriteLine($"Here is your gift, {@for[ctr]}!"); } // The example displays the following output: // Here is your gift, John! // Here is your gift, James! // Here is your gift, Joan! // Here is your gift, Jamie!

 

📌실제 적용 코드

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

// Expected output:
// C:\\Users\\Jane\\Documents
// C:\\Users\\Jane\\Documents

@문자열은 $기능과 함께 사용될 수 있습니다.

Console.WriteLine($@"Testing \\n 1 2 {5 - 2}
New line");

//출력:
//-
//Testing \\n 123
//New line - 
  • 중괄호 안의 모든 식들은 해당 위치에 문자열로 삽입되기 전에 계산된다.

 

 

📌Refs


https://learn.microsoft.com/ko-kr/dotnet/csharp/language-reference/tokens/interpolated

https://nochoco-lee.tistory.com/468

 

 

 

 

'이건 알아야지's > C#' 카테고리의 다른 글

C언어 - 메모리의 동적할당  (0) 2023.06.20