반응형
C#의 클래스 중 하나인 string은 문자열을 저장하고 다양한 작업을 수행할 수 있는 유용한 클래스입니다. 이번 블로그에서는 string 클래스에서 자주 쓰이는 메서드들을 자세하게 설명하겠습니다.
Length
문자열의 길이를 반환합니다.
string str = "hello";
int length = str.Length; // 5
IndexOf
지정된 문자열의 인덱스를 반환합니다. 만약 문자열이 없다면 -1을 반환합니다.
string str = "hello world";
int index = str.IndexOf("world"); // 6
Substring
문자열의 일부분을 반환합니다.
string str = "hello world";
string subStr = str.Substring(0, 5); // "hello"
Replace
문자열 내의 특정 문자열을 새로운 문자열로 대체합니다.
string str = "hello world";
string newStr = str.Replace("world", "universe"); // "hello universe"
ToUpper, ToLower
문자열을 대문자 또는 소문자로 변경합니다.
string str = "Hello World";
string upperStr = str.ToUpper(); // "HELLO WORLD"
string lowerStr = str.ToLower(); // "hello world"
Trim
문자열의 앞뒤 공백을 제거합니다.
string str = " hello world ";
string trimmedStr = str.Trim(); // "hello world"
Split
문자열을 지정한 구분자로 나누어 배열로 반환합니다.
string str = "hello,world";
string[] arr = str.Split(','); // ["hello", "world"]
Join
문자열 배열을 지정한 구분자로 연결합니다.
string[] arr = { "hello", "world" };
string joinedStr = string.Join(" ", arr); // "hello world"
Concat
두 개 이상의 문자열을 연결합니다.
string str1 = "hello";
string str2 = "world";
string result = string.Concat(str1, " ", str2); // "hello world"
Contains
지정된 문자열이 포함되어 있는지 여부를 반환합니다.
string str = "hello world";
bool contains = str.Contains("world"); // true
Insert
문자열의 지정된 위치에 문자열을 삽입합니다.
string str = "hello world";
string newStr = str.Insert(5, "there "); // "hello there world"
위와 같은 메서드들을 사용하여 문자열을 다양하게 처리할 수 있습니다. 하지만, 문자열을 처리하는 과정에서 메모리를 많이 사용할 수 있으므로, 문자열 처리가 많은 경우 StringBuilder 클래스를 사용하는 것이 좋습니다.
'C#' 카테고리의 다른 글
객체지향의 5대 원칙 SOLID : Open-Closed Principle (0) | 2023.04.28 |
---|---|
객체지향의 5대 원칙 SOLID : Single Responsibility Principle (0) | 2023.04.27 |
C# : Refactoring (0) | 2023.04.20 |
C# 추상 클래스란? (0) | 2023.04.19 |
C# : LINQ (0) | 2023.04.18 |