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)

public char this[
	int index
] { get; set; }

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.

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

Windows 7, Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2008 R2, Windows Server 2008, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98, Windows CE, Windows Mobile for Smartphone, Windows Mobile for Pocket PC, Xbox 360, Zune

The .NET Framework and .NET Compact Framework do not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

.NET Framework

Supported in: 3.5, 3.0, 2.0, 1.1, 1.0

.NET Compact Framework

Supported in: 3.5, 2.0, 1.0

XNA Framework

Supported in: 3.0, 2.0, 1.0

Community Additions

ADD
Show:
© 2014 Microsoft