Llegeix en anglès

Comparteix a través de


String.Length Propiedad

Definición

Obtiene el número de caracteres del objeto String actual.

public int Length { get; }

Valor de propiedad

Número de caracteres de la cadena actual.

Ejemplos

En el ejemplo siguiente se muestra la Length propiedad .

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

Comentarios

La Length propiedad devuelve el número de objetos de Char esta instancia, no el número de caracteres Unicode. El motivo es que un carácter Unicode podría representarse mediante más de un Char. Use la System.Globalization.StringInfo clase para trabajar con cada carácter Unicode en lugar de con cada Char.

En algunos lenguajes, como C y C++, un carácter NULL indica el final de una cadena. En .NET, un carácter NULL se puede incrustar en una cadena. Cuando una cadena incluye uno o varios caracteres NULL, se incluyen en la longitud de la cadena total. Por ejemplo, en la cadena siguiente, las subcadenas "abc" y "def" están separadas por un carácter NULO. La Length propiedad devuelve 7, que indica que incluye los seis caracteres alfabéticos, así como el carácter null.

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

Se aplica a

Producte Versions
.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

Consulte también