StringBuilder.Chars[Int32] 속성

정의

이 인스턴트에서 특정 위치에 있는 문자를 가져오거나 설정합니다.

public:
 property char default[int] { char get(int index); void set(int index, char value); };
public char this[int index] { get; set; }
member this.Chars(int) : char with get, set
Default Public Property Chars(index As Integer) As Char

매개 변수

index
Int32

문자의 위치입니다.

속성 값

index 위치에 있는 유니코드 문자입니다.

예외

문자를 설정하는 동안 index가 이 인스턴스의 범위를 벗어납니다.

문자를 가져오는 동안 index가 이 인스턴스의 범위를 벗어납니다.

설명

index 매개 변수는 내에서 문자의 위치입니다StringBuilder. 문자열의 첫 번째 문자는 인덱스 0입니다. 문자열의 길이는 문자열에 포함된 문자 수입니다. instance 마지막으로 액세스할 수 있는 StringBuilder 문자는 인덱스 Length - 1입니다.

Chars[Int32] 는 클래스의 기본 속성입니다 StringBuilder . C#에서는 인덱서입니다. 즉, 문자열의 알파벳, 공백 및 문장 부호 문자 수를 계산하는 다음 예제와 같이 속성에서 Chars[Int32] 개별 문자를 검색할 수 있습니다.

using System;
using System.Text;

public class Example
{
   public static void Main()
   {
      int nAlphabeticChars = 0;
      int nWhitespace = 0;
      int nPunctuation = 0;  
      StringBuilder sb = new StringBuilder("This is a simple sentence.");
      
      for (int ctr = 0; ctr < sb.Length; ctr++) {
         char ch = sb[ctr];
         if (Char.IsLetter(ch)) { nAlphabeticChars++;  continue; }
         if (Char.IsWhiteSpace(ch)) { nWhitespace++;  continue; }
         if (Char.IsPunctuation(ch)) nPunctuation++;  
      }    

      Console.WriteLine("The sentence '{0}' has:", sb);
      Console.WriteLine("   Alphabetic characters: {0}", nAlphabeticChars);
      Console.WriteLine("   White-space characters: {0}", nWhitespace);
      Console.WriteLine("   Punctuation characters: {0}", nPunctuation);
   }
}
// The example displays the following output:
//       The sentence 'This is a simple sentence.' has:
//          Alphabetic characters: 21
//          White-space characters: 4
//          Punctuation characters: 1
open System
open System.Text

let mutable nAlphabeticChars = 0
let mutable nWhitespace = 0
let mutable nPunctuation = 0  
let sb = StringBuilder "This is a simple sentence."

for i = 0 to sb.Length - 1 do
    let ch = sb[i]
    if Char.IsLetter ch then
        nAlphabeticChars <- nAlphabeticChars + 1
    elif Char.IsWhiteSpace ch then
        nWhitespace <- nWhitespace + 1
    elif Char.IsPunctuation ch then
        nPunctuation <- nPunctuation + 1

printfn $"The sentence '{sb}' has:"
printfn $"   Alphabetic characters: {nAlphabeticChars}"
printfn $"   White-space characters: {nWhitespace}"
printfn $"   Punctuation characters: {nPunctuation}"

// The example displays the following output:
//       The sentence 'This is a simple sentence.' has:
//          Alphabetic characters: 21
//          White-space characters: 4
//          Punctuation characters: 1
Imports System.Text

Module Example
   Public Sub Main()
      Dim nAlphabeticChars As Integer = 0
      Dim nWhitespace As Integer = 0
      Dim nPunctuation As Integer = 0  
      Dim sb As New StringBuilder("This is a simple sentence.")
      
      For ctr As Integer = 0 To sb.Length - 1
         Dim ch As Char = sb(ctr)
         If Char.IsLetter(ch) Then nAlphabeticChars += 1 : Continue For
         If Char.IsWhiteSpace(ch) Then nWhitespace += 1 : Continue For
         If Char.IsPunctuation(ch) Then nPunctuation += 1
      Next    

      Console.WriteLine("The sentence '{0}' has:", sb)
      Console.WriteLine("   Alphabetic characters: {0}", nAlphabeticChars)
      Console.WriteLine("   White-space characters: {0}", nWhitespace)
      Console.WriteLine("   Punctuation characters: {0}", nPunctuation)
   End Sub
End Module
' The example displays the following output:
'       The sentence 'This is a simple sentence.' has:
'          Alphabetic characters: 21
'          White-space characters: 4
'          Punctuation characters: 1

Chars[] 속성에서 문자 기반 인덱싱을 사용하면 다음과 같은 조건 하에서 성능이 매우 느려질 수 있습니다.

각 문자 액세스가 인덱싱할 올바른 버퍼를 찾기 위해 연결된 전체 청크 목록을 확인하기 때문에 성능이 심각하게 저하됩니다.

참고

큰 "청키" StringBuilder 개체의 경우에도 하나 또는 적은 수의 문자에 대한 인덱스 기반 액세스에 속성을 사용하면 Chars[] 성능에 미치는 영향이 미미합니다. 일반적으로 O(n) 작업입니다. StringBuilder 개체에서 문자를 반복할 때 성능에 상당한 영향이 발생합니다. O(n^2)개 작업에 영향을 줍니다.

StringBuilder 개체에서 문자 기반 인덱싱을 사용할 때 성능 문제가 발생하는 경우 다음 방법 중 하나를 사용할 수 있습니다.

  • ToString 메서드를 호출하여 StringBuilder 인스턴스를 String으로 변환한 다음, 문자열의 문자에 액세스합니다.

  • 기존 StringBuilder 개체의 콘텐츠를 크기가 미리 지정된 새로운 StringBuilder 개체로 복사합니다. 새로운 StringBuilder 개체가 청크가 아니기 때문에 성능이 향상됩니다. 예를 들면 다음과 같습니다.

    // sbOriginal is the existing StringBuilder object
    var sbNew = new StringBuilder(sbOriginal.ToString(), sbOriginal.Length);
    
    ' sbOriginal is the existing StringBuilder object
    Dim sbNew = New StringBuilder(sbOriginal.ToString(), sbOriginal.Length)
    
  • StringBuilder(Int32) 생성자를 호출하여 StringBuilder 개체의 초기 용량을 예상된 최대 크기와 대략 동일한 값으로 설정합니다. StringBuilder가 거의 최대 용량에 도달하더라도 메모리의 전체 블록을 할당합니다.

적용 대상

추가 정보