다음을 통해 공유


문자열

업데이트: 2007년 11월

C# 문자열은 string 키워드를 사용하여 선언되는 하나 이상의 문자로 된 그룹입니다. 이 키워드는 System.String 클래스에 상응하는 C# 언어의 기능입니다. C#의 문자열은 C 또는 C++의 문자 배열에 비해 사용이 훨씬 간단하고 프로그래밍 오류가 적게 발생합니다.

문자열 리터럴은 다음 예제에서처럼 따옴표를 사용하여 선언됩니다.

string greeting = "Hello, World!";

다음과 같이 부분 문자열을 추출하고 문자열을 연결할 수 있습니다.

string s1 = "A string is more ";
string s2 = "than the sum of its chars.";

// Concatenate s1 and s2. This actually creates a new
// string object and stores it in s1, releasing the
// reference to the original object.
s1 += s2;

System.Console.WriteLine(s1);
// Output: A string is more than the sum of its chars.

문자열 개체는 일단 만든 후에는 변경할 수 없는 개체입니다. 문자열에 대해 동작하는 메서드는 실제로 새 문자열 개체를 반환합니다. 따라서, 성능상의 이유로 대용량의 연결이나 관련된 다른 문자열 조작 작업은 아래의 코드 예제에서처럼 StringBuilder 클래스를 사용하여 수행해야 합니다.

문자열 작업

이스케이프 문자

"\n"(줄 바꿈) 및 "\t"(탭) 등의 이스케이프 문자를 문자열에 포함할 수 있습니다. 예를 들어, 다음 줄은

string columns = "Column 1\tColumn 2\tColumn 3";
//Output: Column 1        Column 2        Column 3

string rows = "Row 1\r\nRow 2\r\nRow 3";
/* Output:
  Row 1
  Row 2
  Row 3
*/

string title = "\"The \u00C6olean Harp\", by Samuel Taylor Coleridge";
//Output: "The Æolean Harp", by Samuel Taylor Coleridge

다음 줄과 동일합니다.

Hello

World!

백슬래시를 포함하려면 앞에 백슬래시가 하나 더 있어야 합니다. 예를 들어, 다음 문자열은

         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."

다음 문자열과 동일합니다.

\\My Documents\

@ 기호

@ 기호는 문자열을 만들 때 이스케이프 문자와 줄 바꿈을 무시하도록 지정합니다. 따라서 다음 두 개의 문자열은 동일합니다.

string p1 = "\\\\My Documents\\My Files\\";
string p2 = @"\\My Documents\My Files\";

ToString()

모든 C# 기본 제공 데이터 형식에서는 값을 문자열로 변환하는 ToString 메서드를 제공합니다. 이 메서드를 사용하면 다음과 같이 숫자 값을 문자열로 변환할 수 있습니다.

int year = 1999;
string msg = "Eve was born in " + year.ToString();
System.Console.WriteLine(msg);  // outputs "Eve was born in 1999"

개별 문자 액세스

Substring, ReplaceSplitTrim 등의 메서드를 사용하여 문자열에 포함된 개별 문자에 액세스할 수 있습니다.

string s3 = "Visual C# Express";
System.Console.WriteLine(s3.Substring(7, 2));
// Output: "C#"

System.Console.WriteLine(s3.Replace("C#", "Basic"));
// Output: "Visual Basic Express"

// Index values are zero-based
int index = s3.IndexOf("C");
// index = 7

또한 다음과 같이 문자를 문자 배열에 복사할 수 있습니다.

string question = "hOW DOES mICROSOFT wORD DEAL WITH THE cAPS lOCK KEY?";
System.Text.StringBuilder sb = new System.Text.StringBuilder(question);

for (int j = 0; j < sb.Length; j++)
{
    if (System.Char.IsLower(sb[j]) == true)
        sb[j] = System.Char.ToUpper(sb[j]);
    else if (System.Char.IsUpper(sb[j]) == true)
        sb[j] = System.Char.ToLower(sb[j]);
}
// Store the new string.
string corrected = sb.ToString();
System.Console.WriteLine(corrected);
// Output: How does Microsoft Word deal with the Caps Lock key?            

다음과 같이 인덱스를 사용하여 문자열의 개별 문자에 액세스할 수 있습니다.

string s5 = "Printing backwards";

for (int i = 0; i < s5.Length; i++)
{
    System.Console.Write(s5[s5.Length - i - 1]);
}
// Output: "sdrawkcab gnitnirP"

대/소문자 바꾸기

문자열의 문자를 대문자 또는 소문자로 변경하려면 다음과 같이 ToUpper() 또는 ToLower()를 사용합니다.

string s6 = "Battle of Hastings, 1066";

System.Console.WriteLine(s6.ToUpper());
// outputs "BATTLE OF HASTINGS 1066"
System.Console.WriteLine(s6.ToLower());
// outputs "battle of hastings 1066"

비교

지역화되지 않은 두 문자열을 비교하는 가장 좋은 방법은 StringComparison.Ordinal 및 StringComparison.OrdinalIgnoreCase와 Equals 메서드를 사용하는 것입니다.

// Internal strings that will never be localized.
string root = @"C:\users";
string root2 = @"C:\Users";

// Use the overload of the Equals method that specifies a StringComparison.
// Ordinal is the fastest way to compare two strings.
bool result = root.Equals(root2, StringComparison.Ordinal);

Console.WriteLine("Ordinal comparison: {0} and {1} are {2}", root, root2,
                    result ? "equal." : "not equal.");

// To ignore case means "user" equals "User". This is the same as using
// String.ToUpperInvariant on each string and then performing an ordinal comparison.
result = root.Equals(root2, StringComparison.OrdinalIgnoreCase);
Console.WriteLine("Ordinal ignore case: {0} and {1} are {2}", root, root2,
                     result ? "equal." : "not equal.");

// A static method is also available.
bool areEqual = String.Equals(root, root2, StringComparison.Ordinal);


// String interning. Are these really two distinct objects?
string a = "The computer ate my source code.";
string b = "The computer ate my source code.";

// ReferenceEquals returns true if both objects
// point to the same location in memory.
if (String.ReferenceEquals(a, b))
    Console.WriteLine("a and b are interned.");
else
    Console.WriteLine("a and b are not interned.");

// Use String.Copy method to avoid interning.
string c = String.Copy(a);

if (String.ReferenceEquals(a, c))
    Console.WriteLine("a and c are interned.");
else
    Console.WriteLine("a and c are not interned.");

또한 문자열 개체에는 한 문자열이 다른 문자열보다 작은지(<) 또는 큰지(>)에 따라 정수 값을 반환하는 CompareTo() 메서드가 있습니다. 문자열을 비교할 때는 유니코드 값을 사용하며, 소문자 값이 대문자 값보다 작습니다.

// Enter different values for string1 and string2 to
// experiement with behavior of CompareTo
string string1 = "ABC";
string string2 = "abc";

int result2 = string1.CompareTo(string2);

if (result2 > 0)
{
    System.Console.WriteLine("{0} is greater than {1}", string1, string2);
}
else if (result2 == 0)
{
    System.Console.WriteLine("{0} is equal to {1}", string1, string2);
}
else if (result2 < 0)
{
    System.Console.WriteLine("{0} is less than {1}", string1, string2);
}
// Output: ABC is less than abc

다른 문자열 내에서 문자열을 검색하려면 IndexOf()를 사용합니다. IndexOf()는 검색 문자열을 찾지 못한 경우 -1을 반환하고, 검색 문자열을 찾은 경우에는 이 문자열이 처음 나타나는 위치의 인덱스(0부터 시작)를 반환합니다.

// Date strings are interpreted according to the current culture.
// If the culture is en-US, this is interpreted as "January 8, 2008",
// but if the user's computer is fr-FR, this is interpreted as "August 1, 2008"
string date = "01/08/2008";
DateTime dt = Convert.ToDateTime(date);            
Console.WriteLine("Year: {0}, Month: {1}, Day: {2}", dt.Year, dt.Month, dt.Day);

// Specify exactly how to interpret the string.
IFormatProvider culture = new System.Globalization.CultureInfo("fr-FR", true);

// Alternate choice: If the string has been input by an end user, you might 
// want to format it according to the current culture:
// IFormatProvider culture = System.Threading.Thread.CurrentThread.CurrentCulture;
DateTime dt2 = DateTime.Parse(date, culture, System.Globalization.DateTimeStyles.AssumeLocal);
Console.WriteLine("Year: {0}, Month: {1}, Day {2}", dt2.Year, dt2.Month, dt2.Day);

/* Output (assuming first culture is en-US and second is fr-FR):
    Year: 2008, Month: 1, Day: 8
    Year: 2008, Month: 8, Day 1
 */

문자열을 부분 문자열로 분할

문장을 개별 단어로 분할하는 것과 같이 문자열을 부분 문자열로 분할하는 것은 일반적인 프로그래밍 작업입니다. Split() 메서드는 공백 문자 등의 구분 기호 char 배열을 받아 부분 문자열의 배열을 반환합니다. 다음과 같이 foreach를 사용하여 이 배열에 액세스할 수 있습니다.

string numString = "1287543"; //"1287543.0" will return false for a long
long number1 = 0;
bool canConvert = long.TryParse(numString, out number1);
if (canConvert == true)
  Console.WriteLine("number1 now = {0}", number1);
else
  Console.WriteLine("numString is not a valid long");

byte number2 = 0;
numString = "255"; // A value of 256 will return false
canConvert = byte.TryParse(numString, out number2);
if (canConvert == true)
  Console.WriteLine("number2 now = {0}", number2);
else
  Console.WriteLine("numString is not a valid byte");

decimal number3 = 0;
numString = "27.3"; //"27" is also a valid decimal
canConvert = decimal.TryParse(numString, out number3);
if (canConvert == true)
  Console.WriteLine("number3 now = {0}", number3);
else
  Console.WriteLine("number3 is not a valid decimal");            

이 코드는 다음과 같이 각 단어를 별도의 줄에 출력합니다.

The

cat

sat

on

the

mat.

StringBuilder 사용

StringBuilder 클래스는 프로그램에서 수행할 문자열 조작 작업이 많을 경우 성능을 향상시켜 주는 문자열 버퍼를 만듭니다. 또한 StringBuilder 클래스를 사용하면 개별 문자를 다시 할당할 수 있습니다. 이러한 기능은 기본 제공 데이터 형식에서는 지원하지 않습니다.

다음 예제에서는 StringBuilder 개체를 만들고, Append 메서드를 사용하여 이 개체의 내용을 하나씩 추가합니다.

class TestStringBuilder
{
    static void Main()
    {
        System.Text.StringBuilder sb = new System.Text.StringBuilder();

        // Create a string composed of numbers 0 - 9
        for (int i = 0; i < 10; i++)
        {
            sb.Append(i.ToString());
        }
        System.Console.WriteLine(sb);  // displays 0123456789

        // Copy one character of the string (not possible with a System.String)
        sb[0] = sb[9];

        System.Console.WriteLine(sb);  // displays 9123456789
    }
}

참고 항목

작업

방법: 여러 줄 문자열 리터럴 생성(Visual C#)

방법: 문자열 배열에서 문자열 검색

방법: 문자열 내에서 검색

개념

C# 언어 입문

기본 제공 데이터 형식(Visual C# Express)

참조

string(C# 참조)