String.Length Propriété
Définition
Important
Certaines informations portent sur la préversion du produit qui est susceptible d’être en grande partie modifiée avant sa publication. Microsoft exclut toute garantie, expresse ou implicite, concernant les informations fournies ici.
Obtient le nombre de caractères dans l’objet actif String .
public:
property int Length { int get(); };
public int Length { get; }
member this.Length : int
Public ReadOnly Property Length As Integer
Valeur de propriété
Nombre de caractères dans la chaîne actuelle.
Exemples
L’exemple suivant illustre la Length propriété.
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
Remarques
La Length propriété retourne le nombre d’objets Char de cette instance, et non le nombre de caractères Unicode. La raison est qu’un caractère Unicode peut être représenté par plusieurs Char. Utilisez la System.Globalization.StringInfo classe pour utiliser chaque caractère Unicode au lieu de chaque Charcaractère .
Dans certains langages, tels que C et C++, un caractère Null indique la fin d’une chaîne. Dans .NET, un caractère Null peut être incorporé dans une chaîne. Lorsqu’une chaîne inclut un ou plusieurs caractères Null, elles sont incluses dans la longueur de la chaîne totale. Par exemple, dans la chaîne suivante, les sous-chaînes « abc » et « def » sont séparées par un caractère Null. La Length propriété retourne 7, ce qui indique qu’elle inclut les six caractères alphabétiques ainsi que le caractère 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