Sdílet prostřednictvím


String.Length Vlastnost

Definice

Získá počet znaků v aktuálním String objektu.

public:
 property int Length { int get(); };
public int Length { get; }
member this.Length : int
Public ReadOnly Property Length As Integer

Hodnota vlastnosti

Počet znaků v aktuálním řetězci.

Příklady

Následující příklad ukazuje Length vlastnost.

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

Poznámky

Vlastnost Length vrátí počet Char objektů v této instanci, nikoli počet znaků Unicode. Důvodem je, že znak Unicode může být reprezentován více než jedním Charznakem . System.Globalization.StringInfo Pomocí třídy můžete pracovat s každým znakem Unicode místo každého Charznaku .

V některých jazycích, například C a C++, znak null označuje konec řetězce. V .NET lze do řetězce vložit znak null. Pokud řetězec obsahuje jeden nebo více znaků null, jsou zahrnuty v délce celkového řetězce. Například v následujícím řetězci jsou podřetězce "abc" a "def" odděleny znakem null. Vlastnost Length vrátí hodnotu 7, která označuje, že obsahuje šest abecedních znaků a také znak 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

Platí pro

Viz také