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 属性。
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
let str = "abcdefg"
printfn $"1) The length of '{str}' is {str.Length}"
printfn $"""2) The length of '{"xyz"}' is {"xyz".Length}"""
let length = str.Length
printfn $"3) The length of '{str}' is {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 字符,而不是每个 CharUnicode 字符。
在某些语言(如 C 和 C++)中,null 字符指示字符串的末尾。 在 .NET 中,null 字符可以嵌入到字符串中。 当字符串包含一个或多个 null 字符时,它们将包含在总字符串的长度中。 例如,在以下字符串中,子字符串“abc”和“def”用 null 字符分隔。 该 Length 属性返回 7,指示它包括六个字母字符和 null 字符。
string characters = "abc\u0000def";
Console.WriteLine(characters.Length); // Displays 7
let characters = "abc\u0000def"
printfn $"{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