String.Chars[Int32] Property

Definition

Gets the Char object at a specified position in the current String object.

public char this[int index] { get; }

Parameters

index
Int32

A position in the current string.

Property Value

The object at position index.

Exceptions

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

Examples

The following example demonstrates how you can use this indexer in a routine to validate a string.

Console.Write("Type a string : ");
string myString = Console.ReadLine();
for (int i = 0; i < myString.Length; i ++)
   if(Uri.IsHexDigit(myString[i]))
      Console.WriteLine("{0} is a hexadecimal digit.", myString[i]);
   else
      Console.WriteLine("{0} is not a hexadecimal digit.", myString[i]);
// The example produces output like the following:
//    Type a string : 3f5EaZ
//    3 is a hexadecimal digit.
//    f is a hexadecimal digit.
//    5 is a hexadecimal digit.
//    E is a hexadecimal digit.
//    a is a hexadecimal digit.
//    Z is not a hexadecimal digit.

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. Use the System.Globalization.StringInfo class to work with Unicode characters instead of Char objects. For more information, see the "Char Objects and Unicode Characters" section in the String class overview.

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.

string str1 = "Test";
for (int ctr = 0; ctr <= str1.Length - 1; ctr++ )
   Console.Write("{0} ", str1[ctr]);
// The example displays the following output:
//      T e s t

Applies to

제품 버전
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

See also