문자열의 불변성
문자열 "수정"은 실제로 새 문자열을 만드는 것이므로 문자열에 대한 참조를 만들 때 주의해야 합니다. 문자열에 대한 참조를 만든 후 원래 문자열을 "수정"하더라도 참조는 문자열을 수정할 때 만든 새 개체가 아니라 원래 개체를 계속 가리킵니다.
string str1 = "Hello "; string str2 = str1; str1 += "World";
System.Console.WriteLine(str2);
//Output: Hello
축자 문자열 리터럴
string filePath = @"C:\\Users\\scoleridge\\Documents";
//Output: C:\\Users\\scoleridge\\Documents\\
string text = @"My pensive SARA ! thy soft cheek reclined
Thus on mine arm, most soothing sweet it is
To sit beside our Cot,...";
/\* Output:
My pensive SARA ! thy soft cheek reclined
Thus on mine arm, most soothing sweet it is
To sit beside our Cot,...
\*/
string quote = @"Her name was ""Sara.""";
//Output: Her name was "Sara."
원시 문자열 리터럴
축자 문자열보다 코드 상에서 보기 편함 (특히, json & xml 형식에) - C# 11 부터 사용가능 - 세 개 이상의 큰따옴표(""") 시퀀스로 시작하고 끝납니다. 세 개 이상의 반복된 따옴표 문자가 포함된 문자열 리터럴을 지원하기 위해 시퀀스를 시작하고 종료할 수 있습니다. - 한 줄 원시 문자열 리터럴에는 같은 줄에 여는 따옴표 문자와 닫는 따옴표 문자가 필요합니다. - 여러 줄 원시 문자열 리터럴에는 자체 줄에 여는 따옴표 문자와 닫는 따옴표 문자가 모두 필요합니다. - 여러 줄 원시 문자열 리터럴에서는 닫는 따옴표 왼쪽의 공백이 모두 제거됩니다.
string singleLine = """Friends say "hello" as they pass by.""";
string multiLine = """
"Hello World!" is typically the first program someone writes.
""";
string embeddedXML = """
Here is the main text
Excerpts from "An amazing story"
</element >
""";
// The line "" starts in the first column.
// All whitespace left of that column is removed from the string.
string rawStringLiteralDelimiter = """"
Raw string literals are delimited
by a string of at least three double quotes,
like this: """
"""";
// CS8997: Unterminated raw string literal.
var multiLineStart = """This
is the beginning of a string
""";
// CS9000: Raw string literal delimiter must be on its own line.
var multiLineEnd = """
This is the beginning of a string """;
// CS8999: Line does not start with the same whitespace as the closing line
// of the raw string literal
var noOutdenting = """
A line of text.
Trying to outdent the second line.
""";
문자열 보간
C# 6.0 이상에서 사용 가능한 ‘보간된 문자열’은 $ 특수 문자로 식별되고 중괄호 안에 보간된 식(형식 문자열)을 포함합니다.
var jh = (firstName: "Jupiter", lastName: "Hammon", born: 1711, published: 1761);
Console.WriteLine($"{jh.firstName} {jh.lastName} was an African American poet born in {jh.born}.");
Console.WriteLine($"He was first published in {jh.published} at the age of {jh.published - jh.born}.");
Console.WriteLine($"He'd be over {Math.Round((2018d - jh.born) / 100d) \* 100d} years old today.");
// Output:
// Jupiter Hammon was an African American poet born in 1711.
// He was first published in 1761 at the age of 50.
// He'd be over 300 years old today.
원시 문자열 결합
int X = 2;
int Y = 3;
var pointMessage = $$"""The point {{{X}}, {{Y}}} is {{Math.Sqrt(X \* X + Y \* Y)}} from the origin.""";
Console.WriteLine(pointMessage);
// Output:
// The point {2, 3} is 3.605551275463989 from the origin.
Null 문자열 및 빈 문자열
null 을 쓰는 것 보다 안정성이 좋음
string str = "hello";
string nullStr = null;
string emptyStr = String.Empty;
string tempStr = str + nullStr;
// Output of the following line: hello
Console.WriteLine(tempStr);
bool b = (emptyStr == nullStr);
// Output of the following line: False
Console.WriteLine(b);
// The following line creates a new empty string.
string newStr = emptyStr + nullStr;
// Null strings and empty strings behave differently. The following
// two lines display 0.
Console.WriteLine(emptyStr.Length);
Console.WriteLine(newStr.Length);
// The following line raises a NullReferenceException.
//Console.WriteLine(nullStr.Length);
// The null character can be displayed and counted, like other chars.
string s1 = "\\x0" + "abc";
string s2 = "abc" + "\\x0";
// Output of the following line: \* abc\*
Console.WriteLine("\*" + s1 + "\*");
// Output of the following line: _abc \*
Console.WriteLine("_" + s2 + "\*");
// Output of the following line: 4
Console.WriteLine(s2.Length);
빠른 문자열 만들기를 위해 stringBuilder 사용
System.Text.StringBuilder sb = new System.Text.StringBuilder("Rat: the ideal pet");
sb\[0\] = 'C';
System.Console.WriteLine(sb.ToString());
//Outputs Cat: the ideal pet
string 값 변경 시, 새로 생성하지 않기 때문에 빠름
var sb = new StringBuilder();
// Create a string composed of numbers 0 - 9
for (int i = 0; i < 10; i++)
{
sb.Append(i.ToString());
}
Console.WriteLine(sb); // displays 0123456789
// Copy one character of the string (not possible with a System.String)
sb\[0\] = sb\[9\];
Console.WriteLine(sb); // displays 9123456789
'공부 > C#' 카테고리의 다른 글
인덱서 (Indexer) (0) | 2024.05.22 |
---|