Leggere in inglese

Condividi tramite


String.Length Proprietà

Definizione

Ottiene il numero di caratteri nell'oggetto String corrente.

C#
public int Length { get; }

Valore della proprietà

Numero di caratteri nella stringa corrente.

Esempio

Nell'esempio seguente viene illustrata la Length proprietà .

C#
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

Commenti

La Length proprietà restituisce il numero di oggetti in questa istanza, non il numero di Char caratteri Unicode. Il motivo è che un carattere Unicode potrebbe essere rappresentato da più di un Charoggetto . Usare la System.Globalization.StringInfo classe per usare ogni carattere Unicode anziché ogni Charoggetto .

In alcuni linguaggi, ad esempio C e C++, un carattere Null indica la fine di una stringa. In .NET un carattere Null può essere incorporato in una stringa. Quando una stringa include uno o più caratteri Null, vengono inclusi nella lunghezza della stringa totale. Nella stringa seguente, ad esempio, le sottostringa "abc" e "def" sono separate da un carattere Null. La Length proprietà restituisce 7, che indica che include i sei caratteri alfabetici e il carattere Null.

C#
string characters = "abc\u0000def";
Console.WriteLine(characters.Length); // Displays 7

Si applica a

Prodotto Versioni
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

Vedi anche