StringBuilder.Chars[Int32] 속성
정의
중요
일부 정보는 릴리스되기 전에 상당 부분 수정될 수 있는 시험판 제품과 관련이 있습니다. Microsoft는 여기에 제공된 정보에 대해 어떠한 명시적이거나 묵시적인 보증도 하지 않습니다.
이 인스턴스의 지정된 문자 위치에 있는 문자를 가져오거나 설정합니다.
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입니다. 문자열의 길이는 문자열에 포함된 문자 수입니다. 인스턴스의 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 인스턴스는 대규모입니다(예: 수만 개의 문자로 구성됩).
- StringBuilder는 '청크형'입니다. 즉, StringBuilder.Append 같은 메서드를 반복 호출하여 개체의 StringBuilder.Capacity 속성을 자동으로 확장하고 새 메모리 청크를 할당하게 됩니다.
각 문자 액세스가 인덱싱할 올바른 버퍼를 찾기 위해 연결된 전체 청크 목록을 확인하기 때문에 성능이 심각하게 저하됩니다.
메모
큰 "chunky" StringBuilder 개체의 경우에도 하나 또는 적은 수의 문자에 대한 인덱스 기반 액세스를 위해 Chars[] 속성을 사용하면 성능에 거의 영향을 미치지 않습니다. 일반적으로 O(n) 연산입니다. StringBuilder 개체에서 문자를 반복할 때 성능에 상당한 영향이 발생합니다. 이는 O(n^2) 연산입니다.
StringBuilder 개체에서 문자 기반 인덱싱을 사용할 때 성능 문제가 발생하는 경우 다음 방법 중 하나를 사용할 수 있습니다.
StringBuilder 메서드를 호출하여 String 인스턴스를 ToString으로 변환한 다음, 문자열의 문자에 액세스합니다.
기존 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 생성자를 호출하여 StringBuilder(Int32) 개체의 초기 용량을 예상된 최대 크기와 대략 동일한 값으로 설정합니다. StringBuilder가 거의 최대 용량에 도달하지 않더라도 메모리의 전체 블록을 할당한다는 점에 유의하세요.