次の方法で共有


String.Length プロパティ

定義

現在の String オブジェクトの文字数を取得します。

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

プロパティ値

現在の文字列内の文字数。

次の例では、 Length プロパティを示します。

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

注釈

Length プロパティは、Unicode 文字の数ではなく、このインスタンス内のCharオブジェクトの数を返します。 その理由は、Unicode 文字が複数の Charで表される可能性があるためです。 System.Globalization.StringInfo クラスを使用して、各Charの代わりに各 Unicode 文字を操作します。

C や C++ などの一部の言語では、null 文字は文字列の末尾を示します。 .NET では、null 文字を文字列に埋め込むことができます。 文字列に 1 つ以上の null 文字が含まれている場合は、合計文字列の長さに含まれます。 たとえば、次の文字列では、部分文字列 "abc" と "def" は null 文字で区切られます。 Length プロパティは 7 を返します。これは、6 文字の英字と 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

適用対象

こちらもご覧ください