기본 콘텐츠로 건너뛰기

C# - StringBuilder

StringBuilder로 할 수 있는 작업들
StringBuilder는 문자열의 내용을 수정하는 메소드들을 제공합니다. 이들을 다음 표로 정리하오니 참고하시기 바랍니다.
원하는 작업
StringBuilder가 제공하는
필드 또는 메소드
사용 예
출력 결과
새로운 문자열을 뒤에 추가한다.StringBuilder Append(string value)StringBuilder strBldr
= new StringBuilder("Super");
strBldr.Append(" Star");
Console.WriteLine(strBldr.ToString());
Super Star

(해설: "Super" 뒤에 " Star"가 추가되어 "Super Star"가 됩니다.)
중간에 문자열을 삽입한다.StringBuilder Insert(
int index, // 이 위치에
string value) // 를 삽입
StringBuilder strBldr
= new StringBuilder("Super Star");
strBldr.Insert(6, "Real ");
Console.WriteLine(strBldr.ToString());
Super Real Star

(해설: 현재 문자열의 6번째 위치는 두번째 S이고, 이 위치부터 문자열 "Real "이 삽입됩니다.)
현재 문자열의 일부를 지운다.StringBuilder Remove(
int startIndex, // 이 위치부터
int length) // length개의 문자들을 제거
StringBuilder strBldr
= new StringBuilder("Super Star");
strBldr.Remove(3, 5);
Console.WriteLine(strBldr.ToString());
Supar
문자열의 일부를 다른 것으로 대체한다.
StringBuilder Replace(
char oldChar, // 를
char newChar) // 로 교체
StringBuilder strBldr
= new StringBuilder("Super Star");
strBldr.Replace('S', 's');
Console.WriteLine(strBldr.ToString());
super star
StringBuilder Replace(
string oldValue, // 를
string newValue) // 로 교체
StringBuilder strBldr
= new StringBuilder(
"One little, two little Indians");
strBldr.Replace("little", "big");
Console.WriteLine(strBldr.ToString());
One big, two big Indians
StringBuilder Replace(
char oldChar, // 를
char newChar, // 로 교체
int startIndex, // 교체 범위의 시작 위치
int count) // startIndex ~ startIndex + count
StringBuilder strBldr
= new StringBuilder(
"One little, two little Indians");
strBldr.Replace('l', 'L', 0, 8);
Console.WriteLine(strBldr.ToString());
One Little, two little Indians
StringBuilder Replace(
string oldValue, // 를
string newValue, // 로 교체
int startIndex, // 교체 범위의 시작 위치
int count) // startIndex ~ startIndex + count
StringBuilder strBldr
= new StringBuilder(
"One little, two little Indians");
strBldr.Replace("little", "big", 15, 10);
Console.WriteLine(strBldr.ToString());
One little, two big Indians
StringBuilder 객체를 string 형으로 바꾼다.
string ToString()StringBuilder strBldr
= new StringBuilder("Hello.");
Console.WriteLine(strBldr.ToString());
Hello.
형식에 맞춘 문자열을 추가하고 싶다.AppendFormat(
string format,
params Object[] args)
string name1 = "Park", name2 = "Son";

StringBuilder strBldr
= new StringBuilder(
"One little, two little Indians");
strBldr.AppendFormat(
"\nTheir names: {0}, {1}",
name1, name2
);

Console.WriteLine(strBldr.ToString());
One little, two little Indians
Their names: Park, Son

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
class StBuilder
 
{
 
        public static void Main()
 
        {
 
            StringBuilder sb = new StringBuilder("Hello");
 
            Console.WriteLine("문자열 {0}", sb);
 
  
 
             
 
            //capacity - 객체의 용량 반환, 50으로 설정해도 자동으로 64로 됨
 
             
 
            Console.WriteLine("해시코드 : {0}, 전체공간 : {1}, 문자열 길이:{2} ", sb.GetHashCode(), sb.Capacity, sb.Length);
 
  
 
            sb.Append("World!!~!~!~~!!!");
 
            Console.WriteLine("문자열 {0}", sb);
 
            Console.WriteLine("해시코드 : {0}, 전체공간 : {1}, 문자열 길이:{2} ", sb.GetHashCode(), sb.Capacity, sb.Length);
 
  
 
            sb.EnsureCapacity(50);
 
            //string 객체를 배열처럼 다룰수도 있음
 
            sb[0] = 'Y';
 
            sb[6] = 'p';
 
            Console.WriteLine("h-y, y-p 변경 : {0}", sb.ToString());   //전체 문자열
 
            Console.WriteLine("해시코드 : {0}, 전체공간 : {1}, 문자열 길이:{2}, 최대 가능 공간 : {3} ", sb.GetHashCode(), sb.Capacity, sb.Length, sb.MaxCapacity);
 
        }
 
}

?
1. 일반적인 사용법
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
using System;
using System.Text;
using System.Diagnostics;
 
class Program
{
    static void Main()
    {
 // 1.
 // Declare a new StringBuilder.
 StringBuilder builder = new StringBuilder();
 
 // 2.
 builder.Append("The list starts here:");
 
 // 3.
 builder.AppendLine();
 
 // 4.
 builder.Append("1 cat").AppendLine();
 
 // 5.
 // Get a reference to the StringBuilder's buffer content.
 string innerString = builder.ToString();
 
 // Display with Debug.
 Debug.WriteLine(innerString);
    }
}

?
2. 교체 및 삽입
1
2
3
4
5
6
7
8
9
10
11
12
13
14
using System;
using System.Text;
 
class Program
{
    static void Main()
    {
 StringBuilder builder = new StringBuilder(
     "This is an example string that is an example.");
 builder.Replace("an", "the"); // Replaces 'an' with 'the'.
 Console.WriteLine(builder.ToString());
 Console.ReadLine();
    }
}

?
3. 루프 foreach 사용
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
using System;
using System.Text;
 
class Program
{
    static void Main()
    {
 string[] items = { "Cat", "Dog", "Celebrity" };
 
 StringBuilder builder2 = new StringBuilder(
     "These items are required:").AppendLine();
 
 foreach (string item in items)
 {
     builder2.Append(item).AppendLine();
 }
 Console.WriteLine(builder2.ToString());
 Console.ReadLine();
    }
}

?
4. 많은 스트링 빌더 사용시
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
using System;
using System.Text;
 
class Program
{
    static string[] _items = new string[]
    {
 "cat",
 "dog",
 "giraffe"
    };
 
    /// <summary>
    /// Append to a new StringBuilder and return it as a string.
    /// </summary>
    static string A1()
    {
 StringBuilder b = new StringBuilder();
 foreach (string item in _items)
 {
     b.AppendLine(item);
 }
 return b.ToString();
    }
 
    static void Main()
    {
 // Called in loop.
 A1();
    }
}





댓글

이 블로그의 인기 게시물

C# - Serial Port ASCII/HEX Format

using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.IO.Ports; namespace SerialTest1 {     public partial class Form1 : Form     {         delegate void MyDelegate();      //델리게이트 선언(크로스 쓰레드 해결하기 위한 용도)         bool SendForamt = true;          // true : ASCII   false : HEX         bool ReceiveFormat = true;       // true : ASCII   false : HEX         public Form1()         {             InitializeComponent();          ...

C# - Windows Form 에 있는 control 찾기

// 아래 코드는 form 의 최상위 control만 찾을 수 있음. // panle, groubbox ... 내부에 있는 control은 찾지 못함. Control GetControlByName(string Name) {     foreach (Control c in this.Controls)         if (c.Name == Name)             return c;     return null; } // form 의 모든 control을 찾을 수 있음. string name = "btnBit" + (i + 1).ToString("D2"); var tmpBtn = this.Controls.Find(name, true).FirstOrDefault(); if (tmpBtn != null) {     if (value == 1) tmpBtn.BackColor = Color.Lime;     else tmpBtn.BackColor = Color.Gray; }

C# - ARGB 색상

속성 A 이  Color  구조체의 알파 구성 요소 값을 가져옵니다. Alice Blue ARGB 값이  #FFF0F8FF 인 시스템 정의 색을 가져옵니다. Antique White ARGB 값이  #FFFAEBD7 인 시스템 정의 색을 가져옵니다. Aqua ARGB 값이  #FF00FFFF 인 시스템 정의 색을 가져옵니다. Aquamarine ARGB 값이  #FF7FFFD4 인 시스템 정의 색을 가져옵니다. Azure ARGB 값이  #FFF0FFFF 인 시스템 정의 색을 가져옵니다. B 이  Color  구조체의 파랑 구성 요소 값을 가져옵니다. Beige ARGB 값이  #FFF5F5DC 인 시스템 정의 색을 가져옵니다. Bisque ARGB 값이  #FFFFE4C4 인 시스템 정의 색을 가져옵니다. Black ARGB 값이  #FF000000 인 시스템 정의 색을 가져옵니다. Blanched Almond ARGB 값이  #FFFFEBCD 인 시스템 정의 색을 가져옵니다. Blue ARGB 값이  #FF0000FF 인 시스템 정의 색을 가져옵니다. Blue Violet ARGB 값이  #FF8A2BE2 인 시스템 정의 색을 가져옵니다. Brown ARGB 값이  #FFA52A2A 인 시스템 정의 색을 가져옵니다. Burly Wood ARGB 값이  #FFDEB887 인 시스템 정의 색을 가져옵니다. Cadet Blue ARGB 값이  #FF5F9EA0 인 시스템 정의 색을 가져옵니다. Chartreuse ARGB 값이  #FF7FFF00 인 시스템 정의 색을 가져옵니다. Chocolate ARGB 값이  #FFD2691E 인 시스템 정의 색을 가져옵니다. Coral ARGB ...