String.Length 屬性
定義
重要
部分資訊涉及發行前產品,在發行之前可能會有大幅修改。 Microsoft 對此處提供的資訊,不做任何明確或隱含的瑕疵擔保。
取得目前 String 物件中字元的數目。
public:
property int Length { int get(); };
public int Length { get; }
member this.Length : int
Public ReadOnly Property Length As Integer
屬性值
目前字串中的字元數。
範例
下列範例會示範 Length 屬性。
// Sample for String::Length
using namespace System;
int main()
{
String^ str = "abcdefg";
Console::WriteLine( "1) The length of '{0}' is {1}", str, str->Length );
Console::WriteLine( "2) The length of '{0}' is {1}", "xyz", ((String^)"xyz")->Length );
int length = str->Length;
Console::WriteLine( "1) The length of '{0}' is {1}", str, length );
}
/*
This example displays the following output:
1) The length of 'abcdefg' is 7
2) The length of 'xyz' is 3
3) The length of 'abcdefg' is 7
*/
string str = "abcdefg";
Console.WriteLine("1) The length of '{0}' is {1}", str, str.Length);
Console.WriteLine("2) The length of '{0}' is {1}", "xyz", "xyz".Length);
int length = str.Length;
Console.WriteLine("3) The length of '{0}' is {1}", str, length);
// This example displays the following output:
// 1) The length of 'abcdefg' is 7
// 2) The length of 'xyz' is 3
// 3) The length of 'abcdefg' is 7
Class Sample
Public Shared Sub Main()
Dim str As String = "abcdefg"
Console.WriteLine("1) The length of '{0}' is {1}", str, str.Length)
Console.WriteLine("2) The length of '{0}' is {1}", "xyz", "xyz".Length)
Dim length As Integer = str.Length
Console.WriteLine("1) The length of '{0}' is {1}", str, length)
End Sub
End Class
'
'This example displays the following output:
' 1) The length of 'abcdefg' is 7
' 2) The length of 'xyz' is 3
' 3) The length of 'abcdefg' is 7
備註
Length屬性 Char 會傳回這個實例中的物件數目,而不是 Unicode 字元數。 原因是 Unicode 字元可能會以一個以上的字元表示 Char 。 使用 System.Globalization.StringInfo 類別來處理每個 Unicode 字元,而不是每個字元 Char 。
在某些語言中,例如 C 和 c + +,null 字元表示字串的結尾。 在 .NET 中,null 字元可以內嵌在字串中。 當字串包含一或多個 null 字元時,它們會包含在總字串的長度中。 例如,在下列字串中,子字串 "abc" 和 "def" 會以 null 字元分隔。 Length屬性會傳回7,表示它包含六個字母字元以及 null 字元。
using namespace System;
using namespace System::Text;
void main()
{
String^ characters = "abc" + L'0' + "def";
Console::WriteLine(characters->Length); // Displays 7
}
string characters = "abc\u0000def";
Console.WriteLine(characters.Length); // Displays 7
Imports System.Text
Module Example
Public Sub Main()
Dim characters As String = "abc" + ChrW(0) + "def"
Console.WriteLine(characters.Length) ' Displays 7
End Sub
End Module