String.Chars[Int32] 屬性

定義

取得目前 Char 物件中指定位置的 String 物件。

C#
public char this[int index] { get; }

參數

index
Int32

目前字串中的位置。

屬性值

Char

index 位置的物件。

例外狀況

index 大於或等於此物件的長度或小於零。

範例

下列範例會示範如何在常式中使用此索引子來驗證字串。

C#
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.

備註

index參數是以零為基底。

這個屬性會 Char 在參數所指定的位置傳回物件 index 。 但是,Unicode 字元可能會以一個以上的字元表示 Char 。 您 System.Globalization.StringInfo 可以使用類別來處理 Unicode 字元,而不是 Char 物件。 如需詳細資訊,請參閱類別總覽中的「Char 物件和 Unicode 字元」一節 String

在 c # 中, Chars[] 屬性是索引子。 在 Visual Basic 中,這是類別的預設屬性 String 。 您 Char 可以使用下列程式碼來存取字串中的每個物件:

C#
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

適用於

產品 版本
.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
.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
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

另請參閱