Upraviť

Zdieľať cez


StringBuilder.Chars[Int32] Property

Definition

Gets or sets the character at the specified character position in this instance.

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

Parameters

index
Int32

The position of the character.

Property Value

The Unicode character at position index.

Exceptions

index is outside the bounds of this instance while setting a character.

index is outside the bounds of this instance while getting a character.

Remarks

The index parameter is the position of a character within the StringBuilder. The first character in the string is at index 0. The length of a string is the number of characters it contains. The last accessible character of a StringBuilder instance is at index Length - 1.

Chars[Int32] is the default property of the StringBuilder class. In C#, it is an indexer. This means that individual characters can be retrieved from the Chars[Int32] property as shown in the following example, which counts the number of alphabetic, white-space, and punctuation characters in a string.

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

Using character-based indexing with the Chars[] property can be extremely slow under the following conditions:

Performance is severely impacted because each character access walks the entire linked list of chunks to find the correct buffer to index into.

Note

Even for a large "chunky" StringBuilder object, using the Chars[] property for index-based access to one or a small number of characters has a negligible performance impact; typically, it is an O(n) operation. The significant performance impact occurs when iterating the characters in the StringBuilder object, which is an O(n^2) operation.

If you encounter performance issues when using character-based indexing with StringBuilder objects, you can use any of the following workarounds:

  • Convert the StringBuilder instance to a String by calling the ToString method, then access the characters in the string.

  • Copy the contents of the existing StringBuilder object to a new pre-sized StringBuilder object. Performance improves because the new StringBuilder object is not chunky. For example:

    // 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)
    
  • Set the initial capacity of the StringBuilder object to a value that is approximately equal to its maximum expected size by calling the StringBuilder(Int32) constructor. Note that this allocates the entire block of memory even if the StringBuilder rarely reaches its maximum capacity.

Applies to

See also