다음을 통해 공유


StringBuilder 클래스

변경할 수 있는 문자열을 나타냅니다. 이 클래스는 상속될 수 없습니다.

네임스페이스: System.Text
어셈블리: mscorlib(mscorlib.dll)

구문

‘선언
<SerializableAttribute> _
<ComVisibleAttribute(True)> _
Public NotInheritable Class StringBuilder
    Implements ISerializable
‘사용 방법
Dim instance As StringBuilder
[SerializableAttribute] 
[ComVisibleAttribute(true)] 
public sealed class StringBuilder : ISerializable
[SerializableAttribute] 
[ComVisibleAttribute(true)] 
public ref class StringBuilder sealed : ISerializable
/** @attribute SerializableAttribute() */ 
/** @attribute ComVisibleAttribute(true) */ 
public final class StringBuilder implements ISerializable
SerializableAttribute 
ComVisibleAttribute(true) 
public final class StringBuilder implements ISerializable

설명

이 클래스는 변경할 수 있는 문자 시퀀스를 값으로 갖는 문자열 형태의 개체를 나타냅니다. 이 값은 문자를 추가, 제거, 교체 및 삽입하여 만든 후에 수정할 수 있으므로 변경 가능합니다. 다른 클래스와 비교하려면 String 클래스를 참조하십시오.

이 클래스의 인스턴스를 수정하는 대부분의 메서드는 이 클래스의 동일한 인스턴스에 대한 참조를 반환합니다. 인스턴스에 대한 참조가 반환되면 이 참조에 대한 메서드나 속성을 호출할 수 있습니다. 이러한 기능은 연속적인 작업을 차례대로 연결하는 단일 문을 작성할 때 유용합니다.

StringBuilder의 용량은 인스턴스가 지정된 시간에 저장할 수 있는 최대 문자 수이며, 인스턴스 값의 문자열 표현 길이보다 크거나 같습니다. Capacity 속성이나 EnsureCapacity 메서드를 사용하여 이 용량을 늘리거나 줄일 수 있지만 Length 속성 값보다 작게 이 용량을 지정할 수는 없습니다.

StringBuilder의 인스턴스가 초기화될 때 지정된 용량이나 최대 용량이 없으면 해당 구현의 기본값이 사용됩니다.

성능 고려 사항

ConcatAppendFormat 메서드는 새 데이터를 기존 String 또는 StringBuilder 개체에 연결합니다. String 개체 연결 작업에서는 항상 기존 문자열과 새 데이터로 새 개체를 만듭니다. StringBuilder 개체는 연결된 새 데이터를 수용할 버퍼를 유지합니다. 새 데이터는 공간이 있을 경우 버퍼 끝에 추가되고, 그렇지 않으면 더 큰 새로운 버퍼가 할당되고, 원래 버퍼의 데이터가 새 버퍼에 복사된 다음, 새 데이터가 새 버퍼에 추가됩니다.

String 또는 StringBuilder 개체에 대한 연결 작업의 성능은 얼마나 자주 메모리를 할당하는지에 따라 달라집니다. StringBuilder 연결 작업에서는 StringBuilder 개체 버퍼가 너무 작아 새 데이터를 넣을 수 없는 경우에만 메모리가 할당되는 반면, String 연결 작업에서는 항상 메모리가 할당됩니다. 따라서 고정된 수의 String 개체를 연결하는 연결 작업에는 String 클래스가 더 적합합니다. 이 경우 개별 연결 작업이 컴파일러를 통해 단일 작업으로 결합될 수 있습니다. 임의의 개수의 문자열을 연결하는(예: 루프에서 임의의 개수의 사용자 입력 문자열을 연결할 경우) 연결 작업에는 StringBuilder 개체가 더 적합합니다.

구현자 참고 사항 이 구현에 대한 기본 용량은 16이고, 기본 최대 용량은 Int32.MaxValue입니다. StringBuilder는 인스턴스의 값이 커지면 문자를 저장하는 데 필요한 메모리를 추가로 할당하므로 용량이 알맞게 조정됩니다. 할당되는 메모리의 양은 구현 방식에 따라 다르고 필요한 메모리의 양이 최대 용량보다 크면 ArgumentOutOfRangeException이 throw됩니다. 예를 들면 Append, AppendFormat, EnsureCapacity, InsertReplace 메서드는 인스턴스의 값을 확대할 수 있습니다. Chars 속성을 사용하면 StringBuilder 값의 개별 문자에 액세스할 수 있습니다. 인덱스 위치는 0부터 시작합니다.

예제

다음 코드 예제에서는 StringBuilder 클래스에서 정의한 여러 메서드를 호출하는 방법을 보여 줍니다.

using System;
using System.Text;

public sealed class App 
{
    static void Main() 
    {
        // Create a StringBuilder that expects to hold 50 characters.
        // Initialize the StringBuilder with "ABC".
        StringBuilder sb = new StringBuilder("ABC", 50);

        // Append three characters (D, E, and F) to the end of the StringBuilder.
        sb.Append(new char[] { 'D', 'E', 'F' });

        // Append a format string to the end of the StringBuilder.
        sb.AppendFormat("GHI{0}{1}", 'J', 'k');

        // Display the number of characters in the StringBuilder and its string.
        Console.WriteLine("{0} chars: {1}", sb.Length, sb.ToString());

        // Insert a string at the beginning of the StringBuilder.
        sb.Insert(0, "Alphabet: ");

        // Replace all lowercase k's with uppercase K's.
        sb.Replace('k', 'K');

        // Display the number of characters in the StringBuilder and its string.
        Console.WriteLine("{0} chars: {1}", sb.Length, sb.ToString());
    }
}

// This code produces the following output.
//
// 11 chars: ABCDEFGHIJk
// 21 chars: Alphabet: ABCDEFGHIJK
using namespace System;
using namespace System::Text;

int main()
{
    // Create a StringBuilder that expects to hold 50 characters.
    // Initialize the StringBuilder with "ABC".
    StringBuilder^ sb = gcnew StringBuilder("ABC", 50);

    // Append three characters (D, E, and F) to the end of the
    // StringBuilder.
    sb->Append(gcnew array<Char>{'D', 'E', 'F'});

    // Append a format string to the end of the StringBuilder.
    sb->AppendFormat("GHI{0}{1}", (Char)'J', (Char)'k');

    // Display the number of characters in the StringBuilder
    // and its string.
    Console::WriteLine("{0} chars: {1}", sb->Length, sb->ToString());

    // Insert a string at the beginning of the StringBuilder.
    sb->Insert(0, "Alphabet: ");

    // Replace all lowercase k's with uppercase K's.
    sb->Replace('k', 'K');

    // Display the number of characters in the StringBuilder
    // and its string.
    Console::WriteLine("{0} chars: {1}", sb->Length, sb->ToString());
}

// This code produces the following output.
//
// 11 chars: ABCDEFGHIJk
// 21 chars: Alphabet: ABCDEFGHIJK

상속 계층 구조

System.Object
  System.Text.StringBuilder

스레드로부터의 안전성

이 형식의 모든 public static(Visual Basic의 경우 Shared) 멤버는 스레드로부터 안전합니다. 인터페이스 멤버는 스레드로부터 안전하지 않습니다.

플랫폼

Windows 98, Windows 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

.NET Framework에서 모든 플래폼의 모든 버전을 지원하지는 않습니다. 지원되는 버전의 목록은 시스템 요구 사항을 참조하십시오.

버전 정보

.NET Framework

2.0, 1.1, 1.0에서 지원

.NET Compact Framework

2.0, 1.0에서 지원

참고 항목

참조

StringBuilder 멤버
System.Text 네임스페이스
String