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
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 字符,而不是每个 Char。
在某些语言(如 C 和 C++)中,null 字符表示字符串的结尾。 在 .NET 中,null 字符可以嵌入到字符串中。 当字符串包含一个或多个 null 字符时,它们包含在总字符串的长度中。 例如,在下面的字符串中,子字符串“abc”和“def”用空字符分隔。 属性 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
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