Was this page helpful?
Your feedback about this content is important. Let us know what you think.
Additional feedback?
1500 characters remaining
Export (0) Print
Expand All

StringBuilder.Chars Property

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

Namespace:  System.Text
Assembly:  mscorlib (in mscorlib.dll)

'Declaration
Public Property Chars ( _
	index As Integer _
) As Char

Parameters

index
Type: System.Int32

The position of the character.

Property Value

Type: System.Char
The Unicode character at position index.

ExceptionCondition
ArgumentOutOfRangeException

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

IndexOutOfRangeException

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

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 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 property as shown in the following example, which counts the number of alphabetic, white-space, and punctuation characters in a string.

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("   Whitespace 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 
'          Whitespace characters: 4 
'          Punctuation characters: 1

.NET Framework

Supported in: 4.6, 4.5, 4, 3.5, 3.0, 2.0, 1.1

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

XNA Framework

Supported in: 3.0, 2.0, 1.0

Portable Class Library

Supported in: Portable Class Library

Supported in: Windows Phone 8.1

Supported in: Windows Phone Silverlight 8.1

Supported in: Windows Phone Silverlight 8
Show:
© 2015 Microsoft