본문 바로가기
WEB/트라우마 NCS_5

문자열 보간

by 함댕댕 2021. 10. 8.

string aFriend = "Maira";

Console.WriteLine("Hello " + aFriend);

 

{  } 문자 사이에 변수를 배치하여 텍스트를 변수 값으로 바꾸도록 C#에 지시할 수 있습니다.

이를 문자열 보간이라고 합니다.

문자열의 여는 따옴표 앞에 $를 추가하면 중괄호 사이 문자열 안에 aFriend 같은 변수를 포함할 수 있습니다.

 

 

Console.WriteLine($"Hello {aFriend}");  //Hello Maira

 

중괄호 사이에는 단일 변수로 제한되지 않습니다. 다음과 같이 해보세요.

C#복사

 

string firstFriend = "Maria";

string secondFriend = "Sage";

Console.WriteLine($"My friends are {firstFriend} and {secondFriend}");     //My friends are Maria and Sage

문자열을 자세히 살펴보면 해당 문자열이 문자 모음 이상의 의미가 있음을 알 수 있습니다.

Length를 사용하여 문자열의 길이를 찾을 수 있습니다.

Length는 문자열의 속성 이고 해당 문자열의 문자 수를 반환합니다.

 

Console.WriteLine($"The name {firstFriend} has {firstFriend.Length} letters.");   // The name Maria has 5 letters.

Console.WriteLine($"The name {secondFriend} has {secondFriend.Length} letters.");   //The name Sage has 4 letters.

 

 

문자열을 조작하는 메서드는 수정하기보다는 새 문자열 개체를 반환합니다. 

Trim 메서드에 대한 각 호출은 새 문자열을 반환하지만 원래 메시지는 변경하지 않습니다.

string greeting = "      Hello World!       "; 대괄호는 공백이 시작되고 끝나는 위치를 표시합니다.
Console.WriteLine($"[{greeting}]"); [      Hello World!       ]
string trimmedGreeting = greeting.TrimStart(); TrimStart(); 시작점정렬
Console.WriteLine($"[{trimmedGreeting}]"); [Hello World!       ]
trimmedGreeting = greeting.TrimEnd(); .TrimEnd(); 끝으로정렬
Console.WriteLine($"[{trimmedGreeting}]"); [      Hello World!]
string sayHello = "Hello World!";  
Console.WriteLine(sayHello);
Hello World!
sayHello = sayHello.Replace("Hello", "Greetings"); 하위 문자열을 검색하여 다른 텍스트로 바꿉니다. 
Replace 메서드는 두 매개 변수 를 사용합니다. 
Console.WriteLine(sayHello); Greetings World!
   
Console.WriteLine(sayHello.ToUpper()); GREETINGS WORLD!
Console.WriteLine(sayHello.ToLower()); greetings world!

 

 

Contains 메서드 : 문자열에 하위 문자열이 포함되어 있는지 여부를 알려 줍니다. 

유사한 메서드 StartsWith  EndsWith가 있습니다.

 

            string songLyrics = "You say goodbye, and I say hello";

 

            Console.WriteLine(songLyrics.Contains("goodbye")); //True

            Console.WriteLine(songLyrics.Contains("greetings")); //False

 

            Console.WriteLine(songLyrics.StartsWith("You")); //True

            Console.WriteLine(songLyrics.EndsWith("greetings")); //False

            Console.WriteLine(songLyrics.EndsWith("You say goodbye, and I say hello")); //True

            Console.WriteLine(songLyrics.EndsWith("ay hello")); //True

댓글