본문 바로가기
C#

[C#] StringBuilder

by DANEW 2023. 6. 27.

StringBuilder (System.Text.StringBuilder)

 

StringBuilder Class (System.Text)

Represents a mutable string of characters. This class cannot be inherited.

learn.microsoft.com

 

[System.Runtime.InteropServices.ComVisible(true)] public sealed class StringBuilder : System.Runtime.Serialization.ISerializable

 

가변이 문자열

 

Append

AppendLine

AppendFormat

Insert

Remove

Replace

인덱서

Length

 

Length가 0이 되면 내용을 지운것으로 처리한다

단, 메모리 상에는 내용이 남아있으므로 인스턴스가 해제되어야 실제로 내용이 지워짐

 

// StringBuilder - 가변이 문자열

 

StringBuilder sb = new StringBuilder();

StringBuilder sb2 = new StringBuilder();

 

for(int i = 0; i < 10; i++)

{

    // 아래 문장 보다는

    // sb.Append(i + ",");

 

    // 이쪽이 성능 면에서 더 낫다

    sb.Append(i);

    sb.Append(",");

 

 

    // Format Append 버전

    sb2.AppendFormat("{0} = ", i);

 

    // 줄바꿈이 있는 Append, overload가 안되어 있어서 직접 string으로 바꿔줘야 함

    sb2.AppendLine(i.ToString());   

}

반응형

Console.WriteLine(sb);

Console.WriteLine(sb2);

Console.WriteLine();

 

// Insert, Remove, Replace, Indexer, Length

Console.WriteLine(sb.Insert(2, "-sigong-"));

Console.WriteLine(sb.Remove(10, 3));

Console.WriteLine(sb.Replace(',', '_'));

Console.WriteLine(sb[3]);

Console.WriteLine(sb.Length);

Console.WriteLine();

          

 

// 길이를 0으로 바꾸면 내용을 비울 수 있다.

// 단 할당된 문자열은 그대로 남아서 메모리를 차지하고 있다.

// 인스턴스가 범위 밖으로 나가면 GC가 수거해간다.

sb.Length = 0;

Console.WriteLine(sb);

 

반응형

'C#' 카테고리의 다른 글

[C#] TimeZoneInfo  (2) 2023.08.11
[C#] TimeZone  (1) 2023.08.10
[C#] DateTime & DateTimeOffset  (0) 2023.07.06
[C#] TimeZoneInfo  (2) 2023.07.05
[C#] TimeZone  (1) 2023.07.04
[C#] TimeSpan  (1) 2023.07.01
[C#] Encoding  (1) 2023.06.30
[C#] string  (0) 2023.06.25