C#에서 string 키워드는 System.String 클래스의 별칭(alias)입니다. 즉, string과 String은 사실상 동일한 타입을 가리키며, 문자열 데이터를 다루는 데 필수적인 다양한 기능을 제공합니다.
참고로 C#의 문자열은 불변(immutable) 객체입니다. 한 번 생성된 문자열은 수정할 수 없으며, 문자열을 조작하면 항상 새로운 문자열 객체가 반환됩니다.
String 클래스의 주요 속성
String 클래스가 제공하는 대표적인 속성은 다음과 같습니다.
| 번호 | 속성 및 설명 |
|---|---|
| 1 | Chars 현재 String 객체에서 지정된 위치에 있는 Char 객체를 가져옵니다. |
| 2 | Length 현재 String 객체에 포함된 문자 수를 가져옵니다. |
String 클래스의 주요 메서드
문자열 비교와 연결에 자주 사용되는 메서드들은 다음과 같습니다.
| 번호 | 메서드 및 설명 |
|---|---|
| 1 | public static int Compare(string strA, string strB) 지정된 두 문자열 객체를 비교하고, 정렬 순서에서의 상대적 위치를 나타내는 정수를 반환합니다. |
| 2 | public static int Compare(string strA, string strB, bool ignoreCase) 두 문자열 객체를 비교하여 정렬 순서상의 상대적 위치를 나타내는 정수를 반환합니다. 단, 불리언 매개변수가 true이면 대소문자를 구분하지 않습니다. |
| 3 | public static string Concat(string str0, string str1) 두 개의 문자열 객체를 하나로 연결합니다. |
| 4 | public static string Concat(string str0, string str1, string str2) 세 개의 문자열 객체를 하나로 연결합니다. |
| 5 | public static string Concat(string str0, string str1, string str2, string str3) 네 개의 문자열 객체를 하나로 연결합니다. |
문자열 생성 및 결합 예제
다음 예제는 문자열 배열을 만들고, String.Join() 메서드를 사용해 여러 문자열을 줄바꿈 문자(\n)로 연결하는 방법을 보여줍니다.
예제 코드
using System;
namespace StringApplication {
class StringProg {
static void Main(string[] args) {
string[] starray = new string[]{"Cricket is my life",
"It is played between two teams",
"It has three formats",
"T20, Test Cricket and ODI",
"Cricket is life"
};
string str = String.Join("\n", starray);
Console.WriteLine(str);
}
}
}실행 결과
Cricket is my life It is played between two teams It has three formats T20, Test Cricket and ODI Cricket is life
위 예제처럼 String.Join()을 활용하면 배열에 담긴 여러 문자열을 원하는 구분자로 손쉽게 하나의 문자열로 합칠 수 있습니다. 이는 콤마로 구분된 목록(CSV)을 만들거나, 여러 줄의 텍스트를 출력할 때 특히 유용합니다.