String.Chars[Int32] 屬性

定義

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

public:
 property char default[int] { char get(int index); };
public char this[int index] { get; }
member this.Chars(int) : char
Default Public ReadOnly Property Chars(index As Integer) As Char

參數

index
Int32

目前字串中的位置。

屬性值

Char

index 位置的物件。

例外狀況

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

範例

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

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.
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.
Console.Write("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
      Console.WriteLine("{0} is a hexadecimal digit.", myString.Chars(i))
   Else
      Console.WriteLine("{0} is not a hexadecimal digit.", myString.Chars(i))
   End If 
Next
' 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 可以使用下列程式碼來存取字串中的每個物件:

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
Dim str1 As String = "Test"
For ctr As Integer = 0 to str1.Length - 1
   Console.Write("{0} ", str1(ctr))
Next   
' The example displays the following output:
'      T e s t

適用於

另請參閱