String.Length Propriedade
Definição
Importante
Algumas informações dizem respeito a um produto pré-lançado que pode ser substancialmente modificado antes de ser lançado. A Microsoft não faz garantias, de forma expressa ou implícita, em relação à informação aqui apresentada.
Obtém o número de caracteres no objeto atual String .
public:
property int Length { int get(); };
public int Length { get; }
member this.Length : int
Public ReadOnly Property Length As Integer
Valor de Propriedade
O número de caracteres na cadeia atual.
Exemplos
O exemplo seguinte demonstra a Length propriedade.
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
Observações
A Length propriedade devolve o número de Char objetos neste caso, não o número de caracteres Unicode. A razão é que um carácter Unicode pode ser representado por mais do que um Char. Use a System.Globalization.StringInfo classe para trabalhar com cada carácter Unicode em vez de cada Char.
Em algumas linguagens, como C e C++, um carácter nulo indica o fim de uma cadeia. No .NET, um carácter nulo pode ser embutido numa cadeia. Quando uma cadeia inclui um ou mais caracteres nulos, estes são incluídos no comprimento total da cadeia. Por exemplo, na sequência seguinte, as substrings "abc" e "def" são separadas por um carácter nulo. A Length propriedade devolve 7, o que indica que inclui os seis caracteres alfabéticos, bem como o carácter nulo.
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