Partager via


String.Chars Property

Microsoft Silverlight will reach end of support after October 2021. Learn more.

Gets the character at a specified character position in the current string.

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

Syntax

'Declaration
Public ReadOnly Property Chars ( _
    index As Integer _
) As Char
public char this[
    int index
] { get; }

Parameters

  • index
    Type: System.Int32
    A character position in the current string.

Property Value

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

Exceptions

Exception Condition
IndexOutOfRangeException

index is greater than or equal to the length of this object or less than zero.

Remarks

The index parameter is zero-based.

This property returns the Char object at the position specified by the index parameter. However, a Unicode character might be represented by more than one Char object. Use the System.Globalization.StringInfo class to work with Unicode characters instead of Char objects.

In C#, the Chars property is an indexer. In Visual Basic, it is the default property of the String class. Each Char object in the string can be accessed by using code such as the following.

Dim str1 As String = "Test"
For ctr As Integer = 0 To str1.Length - 1
   outputBlock.Text += String.Format("{0} ", str1(ctr))
Next
' The example displays the following output:
'      T e s t         
string str1 = "Test";
for (int ctr = 0; ctr <= str1.Length - 1; ctr++)
   outputBlock.Text += String.Format("{0} ", str1[ctr]);
// The example displays the following output:
//      T e s t         

Examples

The following code example demonstrates how you can use the Chars property in a routine to validate a string.

outputBlock.Text += "Type a string : "
Dim myString As String = Console.ReadLine()
Dim i As Integer
For i = 0 To myString.Length - 1
   If Uri.IsHexDigit(myString.Chars(i)) Then
      outputBlock.Text += String.Format("{0} is a hexadecimal digit.", myString.Chars(i)) + vbCrLf
   Else
      outputBlock.Text += String.Format("{0} is not a hexadecimal digit.", myString.Chars(i)) + vbCrLf
   End If
outputBlock.Text += "Type a string : ";
string myString = Console.ReadLine();
for (int i = 0; i < myString.Length; i++)
   if (Uri.IsHexDigit(myString[i]))
      outputBlock.Text += String.Format("{0} is a hexadecimal digit.", myString[i]) + "\n";
   else
      outputBlock.Text += String.Format("{0} is not a hexadecimal digit.", myString[i]) + "\n";

Version Information

Silverlight

Supported in: 5, 4, 3

Silverlight for Windows Phone

Supported in: Windows Phone OS 7.1, Windows Phone OS 7.0

XNA Framework

Supported in: Xbox 360, Windows Phone OS 7.0

Platforms

For a list of the operating systems and browsers that are supported by Silverlight, see Supported Operating Systems and Browsers.

See Also

Reference